Combine column to remove NA's

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

    In a related link (suppress NAs in paste()) I present a version of paste with a na.rm option (with the unfortunate name of paste5).

    With this the code becomes

    cols <- c("x", "y", "z")
    cbind.data.frame(a = data$a, mycol = paste2(data[, cols], na.rm = TRUE))
    

    The output of paste5 is a character, which works if you have character data otherwise you'll need to coerce to the type you want.

提交回复
热议问题