【发布时间】:2011-04-01 01:21:15
【问题描述】:
我将以下数据作为名为“data_old”的数据框读入 R:
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
. . ... .
. . ... .
我编写了一个小循环,它遍历数据并总结每个月/年组合的 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")}
}
}
我的问题是:我可以在终端中打印每个月/年组合的总和,但是如何将其存储在向量中? (嵌套循环让我很头疼试图弄清楚这一点)。
托马斯
【问题讨论】:
标签: r loops statistics nested