我有一组事件数据,大致格式如下:
Incident # Date Year State Criminal Offense Location 155k事件。我想创建一个新的数据帧序列,对未分组的数据进行分组(即,与此链接中的第一步相反:http://ww2.coastal.edu/kingw/statistics/R-tutorials/descriptive.html)。我希望数据帧包含上述最后两列中每一列的每个分类计数的每一年/每个州的总数(但每个年份-州组合只有一行),因此它将是两个单独的数据帧:
Year State Sum of Criminal Offense 1 Sum of Criminal Offense 2 Sum of Crim 3和
Year State Sum of Location 1 Sum of Location 2 Sum of Location 3其目标是按州进行事件计数随时间的比较,或对某一犯罪类型在某一州的总事件进行时间序列预测。我能从未分组的数据中轻松地做到这一点吗?对于分组数据和未分组数据,是否存在分析/预测方法最有效/最实用的资源或一些简短规则?
发布于 2014-05-30 08:49:52
这里提供了一种方法,使用table计算实体数,然后使用reshape将其转换为所需的形式。
假数据:
d <- data.frame(Incident=1:4, Year=c(1,1,2,2), State=c('AL','MN','AL','MN'),Offense=c(1,1,1,2),Location=c(1,2,2,2))
d
## Incident Year State Offense Location
## 1 1 1 AL 1 1
## 2 2 1 MN 1 2
## 3 3 2 AL 1 2
## 4 4 2 MN 2 2位置:
dl <- as.data.frame(xtabs(~Year+State+Location, data=d))
# dl <- as.data.frame(table(Year=d$Year, State=d$State, Location=d$Location))
reshape(dl, direction='wide', timevar='Location', idvar=c('Year', 'State'))
## Year State Freq.1 Freq.2
## 1 1 AL 1 0
## 2 2 AL 0 1
## 3 1 MN 0 1
## 4 2 MN 0 1违规行为:
do <- as.data.frame(xtabs(~Year+State+Offense, data=d))
# do <- as.data.frame(table(Year=d$Year, State=d$State, Offense=d$Offense))
reshape(do, direction='wide', timevar='Offense', idvar=c('Year', 'State'))
## Year State Freq.1 Freq.2
## 1 1 AL 1 0
## 2 2 AL 1 0
## 3 1 MN 1 0
## 4 2 MN 0 1https://stackoverflow.com/questions/23945024
复制相似问题