[英]How to FOR and IF loop in R to sum values according to two factor levels and create new variable?
[英]Aggregating according to factor levels in R (create new columns?)
我有一个日期数组和一个类别数组。 我想按日期汇总类别数组,计算出现次数。 如果我只是这样做:
array <- aggregate(array$category,by=list(array$date),FUN="length")
我将获得所有类别的事件。 我想要按类别列出每个因素的出现次数。
我有几个数据,每个数据都有自己的类别。 它从5到9个类别不等,并且在每个日期中,您可以拥有不同的类别。
示例数据是:
category dateop
3 05/07/2012
3 05/07/2012
4 05/07/2012
4 05/07/2012
4 05/07/2012
4 05/07/2012
5 05/07/2012
5 05/07/2012
5 05/07/2012
3 05/07/2012
3 05/07/2012
3 05/07/2012
3 03/07/2012
1 04/07/2012
5 05/07/2012
5 05/07/2012
5 05/07/2012
5 05/07/2012
5 05/07/2012
3 05/07/2012
我想我必须创建新的数组,以保留每个类别的出现。 我编写了一个在每个级别上进行for循环并创建一个新数组的函数,但是我想知道是否存在一种更快(且代码更少)的方法。
谢谢!
这是两个可能的简单解决方案(我叫您的数据集df
,尽管它的名称比array
更好)
library(data.table)
setDT(df)[, .(occurrences = .N), .(date, category)]
# date category occurrences
# 1: 05/07/2012 3 6
# 2: 05/07/2012 4 4
# 3: 05/07/2012 5 8
# 4: 03/07/2012 3 1
# 5: 04/07/2012 1 1
要么
library(dplyr)
df %>%
group_by(date, category) %>%
summarise(occurrences = n())
# Source: local data table [5 x 3]
# Groups: date
#
# date category occurrences
# 1 05/07/2012 3 6
# 2 05/07/2012 4 4
# 3 05/07/2012 5 8
# 4 03/07/2012 3 1
# 5 04/07/2012 1 1
或与基数R
df$occurrences <- 1
aggregate(occurrences ~ date + category, df, sum)
# date category occurrences
# 1 04/07/2012 1 1
# 2 03/07/2012 3 1
# 3 05/07/2012 3 6
# 4 05/07/2012 4 4
# 5 05/07/2012 5 8
和@akruns uber矢量化解决方案
subset(as.data.frame(table(df[2:1])), !!Freq)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.