Tho*_*sen 2 statistics loops nested r
我将以下数据读入R作为名为"data_old"的数据框:
yes year month
1 15 2004 5
2 9 2005 6
3 15 2006 3
4 12 2004 5
5 14 2005 1
6 15 2006 7
. . ... .
. . ... .
Run Code Online (Sandbox Code Playgroud)
我写了一个小循环来遍历数据并总结每个月/年组合的yes变量:
year_f <- c(2004:2006)
month_f <- c(1:12)
for (i in year_f){
for (j in month_f){
x <- subset(data_old, month == j & year == i, select="yes")
if (nrow(x) > 0){
print(sum(x))
}
else{print("Nothing")}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我可以在终端中打印每个月/年组合的总和,但是如何将其存储在矢量中?(嵌套循环让我头疼,试图解决这个问题).
托马斯
其他方式,
library(plyr)
ddply(data_old,.(year,month),function(x) sum(x[1]))
year month V1
1 2004 5 27
2 2005 1 14
3 2005 6 9
4 2006 3 15
5 2006 7 15
Run Code Online (Sandbox Code Playgroud)
忘记循环,你想使用聚合函数.最近在这个SO问题中对它们进行了讨论.
with(data_old, tapply(yes, list(year, month), sum))
Run Code Online (Sandbox Code Playgroud)
是众多解决方案之一.
此外,c()
当您没有连接任何东西时,您不需要使用.平原1:12
很好.