【问题标题】:writing the outcome of a nested loop to a vector object in R将嵌套循环的结果写入 R 中的向量对象
【发布时间】: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


    【解决方案1】:

    另一种方式,

    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
    

    【讨论】:

    • ddply(data_old,.(year,month),summarize, yes = sum(yes))
    【解决方案2】:

    忘记循环,您想使用聚合函数。最近在this SO question 中对它们进行了讨论。

    with(data_old, tapply(yes, list(year, month), sum))
    

    是众多解决方案之一。

    另外,当你不连接任何东西时,你不需要使用c()。普通的1:12 就可以了。

    【讨论】:

      【解决方案3】:

      只是添加第三个选项:

      aggregate(yes ~ year + month, FUN=sum, data=data_old)
      

      【讨论】:

      • 国际海事组织,应该这样做。普通程序员更清楚:我们是在聚合,而不是“ddplying”。
      • 这是解决这个问题的好方法,但我的大脑并不适合其他问题的所有选项。 plyr 的好处是我只记得模式:拆分/操作/合并。如果我基于某些列拆分 data.frame 并根据片段操作的结果构建新的 data.frame,则 ddply 是正确的函数。
      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      相关资源
      最近更新 更多