Combine column to remove NA's

后端 未结 10 1630
野的像风
野的像风 2020-11-28 06:44

I have some columns in R and for each row there will only ever be a value in one of them, the rest will be NA\'s. I want to combine these into one column with the non-NA val

10条回答
  •  执笔经年
    2020-11-28 07:08

    Here's a more general (but even simpler) solution which extends to all column types (factors, characters etc.) with non-ordered NA's. The strategy is simply to merge the non-NA values of other columns into your merged column using is.na for indexing:

    data$m = data$x  # your new merged column start with x
    data$m[!is.na(data$y)] = data$y[!is.na(data$y)]  # merge with y
    data$m[!is.na(data$z)] = data$z[!is.na(data$z)]  # merge with z
    
    > data
      a  x  y  z m
    1 A  1 NA NA 1
    2 B  2 NA NA 2
    3 C NA  3 NA 3
    4 D NA NA  4 4
    5 E NA NA  5 5
    

    Note that this will overwrite existing values in m if there are several non-NA values in the same row. If you have a lot of columns you could automate this by looping over colnames(data).

提交回复
热议问题