我有一个数据集,其中包括按年和月列出的案例。有些月份丢失了,我想为这些月份创建案例计数为零的行。

这是一个例子,以及我目前的蛮力方法。感谢您的指点。显然,我是新手。

# fake data
library(plyr)
rm(FakeData)
FakeData <- data.frame(DischargeYear=c(rep(2010, 7), rep(2011,7)),
                       DischargeMonth=c(1:7, 3:9),
                       Cases=trunc(rnorm(14, mean=100, sd=20)))

# FakeData is missing data for some year/months
FakeData

# Brute force attempt to add rows with 0 and then total
for(i in 1:12){
  for(j in 1:length(unique(FakeData$DischargeYear))){
    FakeData <- rbind(FakeData, data.frame(
                DischargeYear=unique(FakeData$DischargeYear)[j],
                DischargeMonth=i,
                Cases=0))
      }
     }

FakeData <- ddply(FakeData, c("DischargeYear","DischargeMonth"), summarise, Cases=sum(Cases))

# FakeData now has every year/month represented
FakeData

最佳答案

使用您的 FakeData 数据框,试试这个:

# Create all combinations of months and years
allMonths <- expand.grid(DischargeMonth=1:12, DischargeYear=2010:2011)
# Keep all month-year combinations (all.x=TRUE) and add in 'Cases' from FakeData
allData <- merge(allMonths, FakeData, all.x=TRUE)
# 'allData' contains 'NA' for missing values. Set them to 0.
allData[is.na(allData)] <- 0
# Print results
allData

关于r - 如何有效地使用 R 添加 0 个案例的汇总行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7729662/

10-12 14:05