A dataframe:
a = c("a", "", "c", "", "e")
b = c(1, 2, 3, 4, 5)
c = c("g", "h", "i", "j", "k")
df = data.frame(a,b,c)
How can I fill column "a" with corresponding values in column "c" when "a" is empty using dplyr. I know how to do it using data.table.
Thank you.
This can be done by mutate
and ifelse
. Please notice that I added stringsAsFactors = FALSE
to avoid the creation of factor columns when creating the data frame because working on character is easier in this case.
a <- c("a", "", "c", "", "e")
b <- c(1, 2, 3, 4, 5)
c <- c("g", "h", "i", "j", "k")
df <- data.frame(a,b,c, stringsAsFactors = FALSE)
library(dplyr)
df2 <- df %>% mutate(a = ifelse(a %in% "", c, a))
df2
# a b c
# 1 a 1 g
# 2 h 2 h
# 3 c 3 i
# 4 j 4 j
# 5 e 5 k
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With