I'm kind of new and still learning R. The few posts I've looked into haven't been very helpful so far.
So, my results' dataframe df.results
looks like this:
| 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
...
So, Flock
ranges from 1 to 322. And Year
goes from 2010 to 2090 in steps of 10 (only 9 different values).
My goal is to create matrices with 322 rows (flocks) and 9 columns (year) with the sum of Heating
(1st matrix) and Cooling
(2nd matrix) per flock per year.
I tried this code:
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)
}}
For some reason, this is not working:
Error in `[<-`(`*tmp*`, i, j, value = sum(df.results$Ventilation[df.results$Flock == : subscript out of bounds
I've tried several ways found online but I can't figure out why mine is not working. I also tried using the "new matrices" as "data frames" with no success.
Much appreciated if anyone can help out or suggest different approaches to make this work.
(P. S. Please let me know if this isn't clear. I'm happy to edit or explain it differently).
Thanks!!