[英]Using Dplyr fill empty cells using corresponding values in another column
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. 当使用dplyr的“ a”为空时,如何在列“ c”中用相应的值填充“ a”列。 I know how to do it using data.table.
我知道如何使用data.table做到这一点。
Thank you. 谢谢。
This can be done by mutate
and ifelse
. 这可以通过
mutate
和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. 请注意,我添加了
stringsAsFactors = FALSE
以避免在创建数据框时创建因子列,因为在这种情况下,处理字符更容易。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.