我正在处理以下四列原始重量测量数据和一个功能非常接近的嵌套 ifelse 语句,该语句导致“kg”向量。
Id G4_R_2_4 G4_R_2_5 G4_R_2_5_option2 kg
219 13237 16.0 NA NA 16.0
220 139129 8.50 55.70 47.20 8.50
221 139215 28.9 NA NA 28.9
222 139216 NA 46.70 8.50 46.70
223 139264 12.40 NA NA 12.40
224 139281 13.60 NA NA 13.60
225 139366 16.10 NA NA 16.10
226 139376 61.80 NA NA 61.80
227 140103 NA 48.60 9.10 48.60
目标是根据以下条件将三个“G4”列合并为 kg:
1) 如果 G4_R_2_4 不是 NA,则打印其值
2) 如果 G4_R_2_4 为 NA,则打印 G4_R_2_5 和 G4_R_2_5_option2 中出现的值中较小的一个(抱歉,变量名很烂)
我一直在使用以下语句(称为“child”的大数据集):
> child$kg <- ifelse(child$G4_R_2_4 == 'NA' & child$G4_R_2_5 < child$G4_R_2_5_option2,
child$G4_R_2_5, ifelse(child$G4_R_2_4 == 'NA' & child$G4_R_2_5 > child$G4_R_2_5_option2,
child$G4_R_2_5_option2, child$G4_R_2_4))
这导致我现在拥有的“kg”向量。它似乎满足 G4_R_2_4 条件(是/不是 NA),但总是打印来自 G4_R_2_5 的 NA 情况的值。我如何让它包含大于/小于条件?
最佳答案
从您的示例中不清楚,但我认为问题在于您正在处理 NA
data.frame
的类型不正确和/或使用了错误的类型的列。尝试像这样重写你的代码:
#if your columns are of character type (warnings are ok)
child$G4_R_2_4<-as.numeric(child$G4_R_2_4)
child$G4_R_2_5<-as.numeric(child$G4_R_2_5)
child$G4_R_2_5_option2<-as.numeric(child$G4_R_2_5_option2)
#correct NA handling
child$kg<-ifelse(is.na(child$G4_R_2_4) & child$G4_R_2_5 <
child$G4_R_2_5_option2, child$G4_R_2_5, ifelse(is.na(child$G4_R_2_4) &
child$G4_R_2_5 > child$G4_R_2_5_option2, child$G4_R_2_5_option2, child$G4_R_2_4))
关于r - R 中的嵌套 ifelse 非常接近工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240278/