【发布时间】:2016-07-04 02:00:57
【问题描述】:
我的数据集基于疾病计数。许多变量是分类变量,例如 WeekSeries、MonthSeries 和 YearSeries。这些标签指的是疾病计数在我的时间序列数据中属于哪个周、月和年。
我面临的问题是构建另一个数据表,该表将根据 WeekSeries、MonthSeries 和 YearSeries 对计数进行求和。我需要我的方法来决定 WeekSeries 1 是编码为 TS1 =1 还是 TS2=1。例如,在原始数据中,您可以看到第三个观察值不属于TS1,而是属于TS2,因为它属于TS2,所以它也有HolidaysPerSeason=10。
我希望该方法决定如果 WeekSeries 1 中的大部分观察属于 TS1=1 和 HolidaysPerSeason =11,那么这将是 WeekSeries=1 的最终类别。
原始数据
WeekSeries Counts TS1 TS2 TS3 TS4 TS5 TS6 HolidaysPerSeason
1 0 1 0 0 0 0 0 11
1 1 1 0 0 0 0 0 11
1 1 0 1 0 0 0 0 10
理想格式
WeekSeries Counts TS1 TS2 TS3 TS4 TS5 TS6 HolidaysPerSeason
1 2 1 0 0 0 0 0 11
这种格式是构建回归模型和其他分析所必需的。
这是与我的真实数据相似的假数据:
# a couple of the variables within my data
JulianDate<-c(10985, 10986,10987)
DateRcd<-c(NA,NA,"2000-01-31")
Counts<-c(0,1,1)
Day<-c("Sat","Sun","Mon")
Weekend<-c(1,1,0)
Season<-c(1,1,2)
HolidaysPerSeason<-c(11,11,10)
TS1<-c(1,1,0)
TS2<-c(0,0,1)
TS3<-c(0,0,0)
TS4<-c(0,0,0)
TS5<-c(0,0,0)
TS6<-c(0,0,0)
WeekSeries<-c(1,1,1)
YearSeries<-c(1,1,1)
MonthSeries<-c(1,1,1)
mydata<-data.table(JulianDate,DateRcd,Counts,Day,Weekend,Season,HolidaysPerSeason, TS1,TS2,TS3,TS4,TS5,TS6,YearSeries,MonthSeries,WeekSeries) #data simulation
我尝试使用 data.table() 函数根据 WeekSeries 进行聚合,然后将其与原始数据合并以构建我理想的分析格式。
我最接近成功的尝试
install.packages("data.table")
library(data.table)
DT <- data.table(mydata)
mydata1<-DT[, by = list(WeekSeries)] #doesn't work
mydata2<-DT[,sum(CountsofCholera), by=WeekSeries] #loses all the other variables
idealdata<-merge(mydata2,mydata,by.x=mydata2$WeekSeries) #attempts to regain the lost variable, this doesn't work because the datasets are not the same length
我可以做些什么来重新获得其他分类变量?
【问题讨论】:
标签: r merge dataframe data.table