使用 rbind 在循环中添加 0 个值

Ale*_*tia 1 grouping loops r sapply rbind

我无法正确编码循环以将行添加到小数据集。

假设我有以下名为“颜色”的数据框:

color   count   group
Blue      3       1
Blue      2       2
Red       2       2
Green     1       1
Run Code Online (Sandbox Code Playgroud)

现在我需要为每列添加 0 个值,以便所有组都有每种颜色,也就是它应该看起来像:

color   count   group
Blue      3       1
Blue      2       2
Red       2       2
Green     1       1
Red       0       1 
Green     0       2
Run Code Online (Sandbox Code Playgroud)

我试图做的最接近我想要的解决方案的是:

color.u <- unique(colors$color)

color.z<- function(x){
  if(x %in% colors$color[colors$group == "1"] == F ) {
    rbind(colors, c(x, 0, "1"))
    }
if(x %in% colors$color[colors$group == "2"] == F ) {
    rbind(colors, c(x, 0, "2"))
    }
}

sapply(color.u, function(x) color.z(x))
Run Code Online (Sandbox Code Playgroud)

这个函数返回的是整个数据集,最后只有两个零值之一。我明白为什么这是一个错误,我相信解决方案很简单,但我不知道如何纠正它。有什么建议?

谢谢!

一种。

Jrm*_*FRL 6

使用tidyr::complete()

complete(data = df, 
         color = levels(color), group = levels(group), 
         fill = list(count = 0))
Run Code Online (Sandbox Code Playgroud)