Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dplyr fill empty cells using corresponding values in another column

Tags:

r

dplyr

tidyverse

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.

like image 274
ip2018 Avatar asked Oct 16 '25 22:10

ip2018


1 Answers

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
like image 158
www Avatar answered Oct 18 '25 13:10

www



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!