Combine column to remove NA's

后端 未结 10 1648
野的像风
野的像风 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:06

    A dplyr::coalesce based solution could be as:

    data %>% mutate(mycol = coalesce(x,y,z)) %>%
             select(a, mycol)
    #   a mycol
    # 1 A     1
    # 2 B     2
    # 3 C     3
    # 4 D     4
    # 5 E     5 
    

    Data

    data <- data.frame('a' = c('A','B','C','D','E'),
                     'x' = c(1,2,NA,NA,NA),
                     'y' = c(NA,NA,3,NA,NA),
                     'z' = c(NA,NA,NA,4,5))
    

提交回复
热议问题