2017-08-26 153 views
-2

我是一個新的,仍然在學習R.到目前爲止,我看過的幾篇文章並沒有很有幫助。下標越界R

所以,我的結果數據幀df.results看起來是這樣的:

  | Age | Flock | Year | Heating | Cooling 
------------------------------------------------------ 
1  | 1 | 1 | 2010 | 266.5788 | 0 
2  | 1 | 1 | 2010 | 275.4562 | 0 
3  | 1 | 1 | 2010 | 285.1423 | 0 
... 
200000 | 15 | 28 | 2020 |-39.84244 | 275.8492 
... 
400000 | 35 | 45 | 2030 |-41.09734 | 284.5375 
...    
900000 | 12 | 300 | 2040 |-42.22414 | 292.3389 
... 
150000 | 22 | 181 | 2050 | 28.9140 | 0 
... 
250000 | 34 | 322 | 2070 | -38.5952 | 430.8928 
... 

所以,Flock範圍爲1〜322而Year從2010年進入到2090,10(9個不同的值)的步驟。

我的目標是創建每年每羣有322行(羣)和9列(年),總和爲Heating(第1矩陣)和Cooling(第2矩陣)的矩陣。

我試過這段代碼:

list.years <- seq(2010, 2090, 10) 
nyears <- length(list.years) 
f <- 322 

sum.heat <- matrix(0, f, length(nyears)) 
sum.cool <- matrix(0, f, length(nyears)) 


for(j in 1:nyears){ 
    for(i in 1:f){ 
     sum.heat[i,j] <- sum(df.results$Heating[df.results$Flock == i], na.rm = TRUE) 
     sum.cool[i,j] <- sum(df.results$Cooling[df.results$Flock == i], na.rm = TRUE) 
}} 

出於某種原因,這是行不通的:

Error in `[<-`(`*tmp*`, i, j, value = sum(df.results$Ventilation[df.results$Flock == : subscript out of bounds 

我試着在網上找到的幾種方法,但我不明白,爲什麼我的是不工作。我也嘗試使用「新的矩陣」作爲「數據框架」,但沒有成功。

非常感謝,如果任何人都可以幫助或建議不同的方法來完成這項工作。 (P. S.請讓我知道如果這不清楚,我很樂意以不同的方式編輯或解釋它)。

謝謝!

回答

0

您可以使用data.table包中的dcast()函數替代double來實現此目的。

# data sample with 2 flocks, 3 years, & 2 entries per year per flock 
set.seed(222) 
df.sample <- data.frame(Flock = c(rep(1, 6), rep(2, 6)), 
         Year = rep(c(2010, 2020, 2030), 4), 
         Heating = rnorm(12, sd = 50), 
         Cooling = rnorm(12, mean = 100, sd = 30)) 

> df.sample 
    Flock Year  Heating Cooling 
1  1 2010 74.38785448 79.22177 
2  1 2020 -0.09459503 118.07947 
3  1 2030 69.05103950 94.06741 
4  1 2010 -19.01068157 64.42376 
5  1 2020 9.20681152 39.83461 
6  1 2030 -12.34479415 100.22530 
7  2 2010 -60.77804548 115.58471 
8  2 2020 78.07025492 77.61114 
9  2 2030 21.36550986 121.79364 
10  2 2010 -60.05117532 121.40970 
11  2 2020 52.62292475 80.49811 
12  2 2030 -65.25317830 144.96089 

library(data.table) 

dcast(dt.sample, Flock~Year, fun = sum, value.var = "Heating") 

    Flock  2010  2020  2030 
1  1 55.37717 9.112216 56.70625 
2  2 -120.82922 130.693180 -43.88767 

dcast(dt.sample, Flock~Year, fun = sum, value.var = "Cooling") 

    Flock  2010  2020  2030 
1  1 143.6455 157.9141 194.2927 
2  2 236.9944 158.1092 266.7545 

p.s.一般來說,在R中使用for循環是一個糟糕的想法。 Patrick Burns的圈子3 The R Inferno對此進行了一些詳細的討論&值得一讀。

+0

非常感謝Z.Lin。它工作得很好。這正是我所期待的。我的C++訓練有素的頭腦保留了循環作爲幾乎所有內容的第一選項。感謝您提供的資源,我認爲它包含不同的包來替代for循環,對嗎? – madmex

+0

@JorgeIzar:對C++來說,對於我們這些有其他語言經驗的人來說,默認循環的願望並不是唯一的。 :)但是,記住R針對向量化函數進行了優化是很好的。人們通常使用的兩個軟件包是'data.table'和[tidyverse](https://www.tidyverse.org/)集合(其中包括'dplyr','tidyr'等)。 [這篇文章](https://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly)比較他們的親戚優點。 –