Replacing NAs in a column with the values of other column

妖精的绣舞 提交于 2019-12-04 11:02:01

问题


I wonder how to replace NAs in a column with the values of other column in R using dplyr. MWE is below.

Letters <- LETTERS[1:5]
Char    <- c("a", "b", NA, "d", NA)
df1 <- data.frame(Letters, Char)
df1

library(dplyr]

df1 %>%
  mutate(Char1 = ifelse(Char != NA, Char, Letters))

     Letters Char Char1
1       A    a    NA
2       B    b    NA
3       C <NA>    NA
4       D    d    NA
5       E <NA>    NA

回答1:


You can use coalesce:

library(dplyr)

df1 <- data.frame(Letters, Char, stringsAsFactors = F)

df1 %>%
  mutate(Char1 = coalesce(Char, Letters))

  Letters Char Char1
1       A    a     a
2       B    b     b
3       C <NA>     C
4       D    d     d
5       E <NA>     E


来源:https://stackoverflow.com/questions/46137115/replacing-nas-in-a-column-with-the-values-of-other-column

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