【问题标题】:R - for loop to create a vector of values from data frameR - for 循环从数据帧创建值向量
【发布时间】:2014-08-05 04:12:59
【问题描述】:

我有一个包含 15,000,000 行的数据框,用于 12 个“天”的观察。此框架中的一列具有每天的值的总和 - 但是对于 1,000 行,这个数字是相同的(每天有很多观察结果)。我需要用 12 个总数制作一个向量,然后剪掉多余的东西。

我在没有 for 循环的情况下成功地做到了:

day1 <- (dat[which(dat$Day == 1), ])[1, 6] # get 1st "Daily.Sum" val of ea. "dat$Day" lev.
day2 <- (dat[which(dat$Day == 2), ])[1, 6] # as "Daily.Sum" is 6th column
day3 <- (dat[which(dat$Day == 3), ])[1, 6]
## ...etc. to "day12"

当我改用这个 for 循环时:

daysums <- as.numeric()
for (i in 1:12) {
      if (dat$Day == i) {
            daysums <- append(daysums, dat[which(dat$Day == i), ][1, 6])
      }
}

我希望得到这个:

daysums
[1] 979426 1240724 1371640 ...etc. #ea. value = 1st obj. in vector "Daily.Sums" for a 
                                   # given day index in vector "dat$Day"

但我收到 12 条警告:

12: In if (dat$Day == i) { ... :
the condition has length > 1 and only the first element will be used

显然我的 for 循环逻辑在这里存在缺陷。任何帮助表示赞赏。

【问题讨论】:

    标签: r for-loop append


    【解决方案1】:

    你可以使用拆分功能

    split(Dat,Dat$day)
    

    【讨论】:

      【解决方案2】:

      试试:with(dat,{tapply(Daily.Sum,Day,mean)})

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多