Replace missing values with a value from another column

若如初见. 提交于 2019-11-28 10:37:39

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)

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.

We can use data.table to assign the values in "Group2" to "Group" where the "Group" is "" specified in the "i" condition.

library(data.table)
setDT(s)[Group=="", Group:= Group2]

As the assignment happens in place, it is considered to be efficient.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!