根据列值添加缺失行的值

时间:2017-06-08 05:55:18

标签: r row add missing-data

我有一个数据框:

things <- data.frame( category = c("A","B","A","B","B","A","B"),
               things2do = c("ball","ball","bat","bat","hockey","volley ball","foos ball"),
                  number = c(12,5,4,1,2,1,1))

现在我想在特定类别和things2do缺失的数字中添加“0”,例如应该添加“A”,“曲棍球”和“0”的新行,同样适用于排球和foos球。

我希望我能在这里得到一些帮助。

2 个答案:

答案 0 :(得分:3)

tidyr的{​​{1}}函数执行此操作:

complete()

输出:

library(tidyr)

things %>%
    complete(category, things2do, fill = list(number = 0))

答案 1 :(得分:1)

我们可以使用expand.grid

中的base R执行此操作
d1 <- merge(expand.grid(category = unique(things$category), 
        things2do = unique(things$things2do)), things, all.x = TRUE)

d1$number[is.na(d1$number)] <- 0
d1
#   category   things2do number
#1         A        ball     12
#2         A         bat      4
#3         A   foos ball      0
#4         A      hockey      0
#5         A volley ball      1
#6         B        ball      5
#7         B         bat      1
#8         B   foos ball      1
#9         B      hockey      2
#10        B volley ball      0

注意:未使用任何外部包