使用 for/if/else 循环用另一列中的文本替换 NA 填充列:R [关闭]

问题描述 投票:0回答:0

如果我能在 if/else 循环方面得到一些帮助,我将不胜感激。我正在尝试使用以下代码替换原始文件中 NA 填充的 Sample_2 列。

最终的 csv 文件一直显示整数而不是字符。我确实确保在读取 csv 期间添加 stringsAsFactors= FALSE 但仍然没有用。

                                                                                
    Day_03_all <- rbind(Common, Day_03) %>% arrange(desc(Sample))

x = Day_03_all$group  ## column with names of group 

y = Day_03_all$Sample ## column filled with "Day_03" and "Common" texts 

for (i in 1:nrow(Day_03_all)){
if(Day_03_all$Sample[i]=="Day_03"){
Day_03_all$Sample_2[i]= x[i]
} 
else{(Day_03_all$Sample[i]=="Common")Day_03_all$Sample_2[i] = y[i]
}
}


## This is what my data looks before:
|exp_mass|group |Sample||Sample_2|
|------  | ---  || --- || --- |
|1 |185.08|CHO||Day_03||NA|
|2 |131.03|CHOS||Day_03||NA|
|3 |199.01 |CHNOS||Common||NA|
|3 |129.01 |CHNO||Common||NA|

##and this is what it looked after:
|exp_mass|group |Sample||Sample_2|
|------  | ---  || --- || --- |
|1 |185.08|CHO||Day_03||1|
|2 |131.03|CHOS||Day_03||1|
|3 |199.01 |CHNOS||Common||Common|
|3 |129.01 |CHNO||Common||Common|





r na
© www.soinside.com 2019 - 2024. All rights reserved.