Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将计数为0的行添加到摘要输出_R_Count_Dplyr_Rows - Fatal编程技术网

R 如何将计数为0的行添加到摘要输出

R 如何将计数为0的行添加到摘要输出,r,count,dplyr,rows,R,Count,Dplyr,Rows,我在下面添加了示例数据,我使用dplyr计算Rco和month: structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 4L, 4L, 4L), .Label = c("A220", "B334", "C123", "D445" ), class = "factor"), month = structure(c(3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 4L, 2L, 4

我在下面添加了示例数据,我使用dplyr计算
Rco
month

structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L, 4L, 4L, 4L), .Label = c("A220", "B334", "C123", "D445"
), class = "factor"), month = structure(c(3L, 2L, 4L, 1L, 3L, 
2L, 4L, 1L, 3L, 4L, 2L, 4L, 3L), .Label = c("Apr", "Feb", "Jan", 
"Mar"), class = "factor"), count = c(1, 2, 3, 4, 5, 6, 7, 8, 
9, 10, 11, 12, 13)), .Names = c("Rco", "month", "count"), row.names = c(NA, 
-13L), class = "data.frame")
是否有方法将此数据转换为:

structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("A220", "B334", 
"C123", "D445"), class = "factor"), month = structure(c(3L, 2L, 
4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L), .Label = c("Apr", 
"Feb", "Jan", "Mar"), class = "factor"), count = c(1, 2, 3, 4, 
5, 6, 7, 8, 9, 0, 10, 0, 13, 11, 12, 0)), .Names = c("Rco", "month", 
"count"), row.names = c(NA, -16L), class = "data.frame")
因此,基本上我需要为所有缺少计数的月份添加额外的行,因为如果不存在
month
-
Rco
组合,则
dplyr::count
不会给出0计数


在我的数据中,月数是可变的(我已经显示了1-2-3-4月,但也可能是12个月),因此如果有人能为我提供动态解决方案,我将不胜感激。

我们可以在前两列的
唯一值上使用
扩展.grid
,并将
与初始数据集合并。这将为
expand.grid
中不存在的组合填充
NA

res <- merge(expand.grid(lapply(df1[1:2], unique)), df1, all.x=TRUE)

我们可以在前两列的
unique
值上使用
expand.grid
,并将
merge
与初始数据集合并。这将为
expand.grid
中不存在的组合填充
NA

res <- merge(expand.grid(lapply(df1[1:2], unique)), df1, all.x=TRUE)

您可以使用
tidyr::complete
并将填充指定为0(而不是默认的NA):


您可以使用
tidyr::complete
并将填充指定为0(而不是默认的NA):


相关问答:相关问答:非常感谢docendo。非常感谢docendo。
library(tidyr)
complete(df, Rco, month, fill = list(count = 0))