问题
I wonder how to replace NA
s 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