1

I have a question similar to the problem raised in this question, however I am not interested in obtaining elementwise means within a list, but for each index value within an element across lists.

Give I have these three lists

ice_2000 = list(seq(1,5,1),seq(6,10,1),seq(11,15,1))
ice_1990 = list(seq(1,5,1),seq(6,10,1),seq(11,15,1))
ice_1980 = list(seq(1,5,1),seq(6,10,1),seq(11,15,1))

I want to find the mean sea ice across years per day per station...

x=c(1,2,3) ## years
y=c(1:5)   ## stations

...and store it in a new list with the same format as any of the three list above

Something like

[[day]][station]....[n station]
.
.
.
[[n day]][station]....[n station]

I have tried something like

average.ice =rep( list(rep(NA, length(y))), 3 ) 

foreach(x=x) %do% {
  foreach(y=y) %do% { 

    average.ice[[x]][y] = mean(c(ice_1980[[x]][y],ice_1990[[x]][y],ice_2000[[x]][y]))

  }
}

But I get NAs in my output

average.ice

[[1]]
[1] 1 2 3

[[2]]
[1] NA NA  8

[[3]]
[1] NA NA 13

Where am I going wrong? is there any smarter way within the apply family?

Community
  • 1
  • 1
Larusson
  • 267
  • 3
  • 21

2 Answers2

1

Take much care with indexes. Is that what you want?

yy=c(1,2,3) ## years
st=c(1:5)   ## stations

average.ice =rep( list(rep(NA, length(st))), 3 ) 

library(foreach)

foreach(x=yy) %do% {
  foreach(y=st) %do% { 

    average.ice[[x]][y] = mean(c(ice_1980[[x]][y],ice_1990[[x]][y],ice_2000[[x]][y]))

  }
}
Robert
  • 5,038
  • 1
  • 25
  • 43
0

You may be looking for something like this:

numOfStations <- length(ice_1980)

average.ice <- lapply(1:numOfStations, 
                      function(i) mapply(mean, ice_1980[[i]], ice_1990[[i]], ice_2000[[i]]))
Psidom
  • 209,562
  • 33
  • 339
  • 356