Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

r - How to add rows with 0 counts to summarised output

I have added sample data below, I have used dplyr to count on Rco and 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")

Is there a way to transform this data to:

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")

So basically I need to add extra rows for all months that have missing count, because dplyr::count does not give 0 counts if a month - Rco combination does not exist.

The number of months is variable in my data ( I have shown Jan Feb Mar Apr but it could be for all 12 months as well) , so please if someone can provide me a dynamic solution, I would be grateful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use tidyr::complete and specify the fill to be 0 (instead of the default NA):

library(tidyr)
complete(df, Rco, month, fill = list(count = 0))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...