簡體   English   中英

R-for循環從數據幀創建值向量

[英]R - for loop to create a vector of values from data frame

我有一個包含15,000萬行的數據框,用於12天的觀察。 此框架中的每一列每天都有一個值的總和-但是此數字對於1000行而言是相同的(每天都有很多觀察結果)。 我需要用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循環邏輯在這里有缺陷。 任何幫助表示贊賞。

您可以使用分割功能

split(Dat,Dat$day)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM