Replace missing values with a value from another column

后端 未结 2 1574
故里飘歌
故里飘歌 2020-12-10 09:13

If I have:

s <- data.frame(ID=c(191, 282, 202, 210), Group=c(\"\", \"A\", \"\", \"B\"), stringsAsFactors=FALSE)
s
   ID Group
1 191      
2 282     A
3 20         


        
相关标签:
2条回答
  • 2020-12-10 10:02

    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.

    0 讨论(0)
  • 2020-12-10 10:08

    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.

    0 讨论(0)
提交回复
热议问题