将缺失的值替换为另一列中的值 [英] Replace missing values with a value from another column
本文介绍了将缺失的值替换为另一列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有
s <- data.frame(ID=c(191, 282, 202, 210), Group=c("", "A", "", "B"), stringsAsFactors=FALSE)
s
ID Group
1 191
2 282 A
3 202
4 210 B
我可以这样用N替换空单元格:
I can replace the empty cells with N like this:
ds$Group[ds$Group==""]<-"N"
s
ID Group
1 191 N
2 282 A
3 202 N
4 210 B
但是我需要用另一列中的值替换空单元格.我该怎么做?:
But I would need to replace the empty cells with a value from another column. How can I accomplish this?:
s
ID Group Group2
1 191 D D
2 282 A G
3 202 G G
4 210 B D
推荐答案
ifelse(test, yes, no)
是一个方便的功能,它可以在矢量上使用.使用最后一个data.frame:
ifelse(test, yes, no)
is a handy function to do just that, and it can be used on vectors. Using your last data.frame:
s <- data.frame(ID = c(191, 282, 202, 210),
Group = c("", "A", "", "B"),
Group2 = c("D", "G", "G", "D"))
s$Group <- ifelse(test = s$Group != "", yes = s$Group, no = s$Group2)
第一个参数是测试.对于向量中的每个值,如果test
为true,则它将采用yes
中的值,否则将采用no
中的值.
The first argument is the test. For each value in the vector, if the test
is true, then it will take the value in yes
, otherwise it will take the value in no
.
这篇关于将缺失的值替换为另一列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文