1

I want to write a loop that extracts a table from a three dimensional array and sequentially write it to a data frame as a column.

The code I have so far is

library(ncdf4)

test <- nc_open("NorESM_TREFHT_cont_mem1-60_2006-2099.nc")
temp <- ncvar_get(test, "TREFHT", count = c(144,96,60,1))
drop(temp)
lat<- ncvar_get(test, "lat")
lon <- ncvar_get(test,"lon")
lonlat <- expand.grid(lon, lat)
for (n in 1:60) {
member <- array(temp[1:144,1:96,n])
ensemble <- as.vector(member)
h <- data.frame(cbind(lonlat, ensemble[n]))
}

Currently the code works without the loop (for n = 1,2 etc.) but only combines the last run in the for loop output for n=1:60

zx8754
  • 52,746
  • 12
  • 114
  • 209
Dylan
  • 37
  • 3

1 Answers1

1

Your h isn't used yet; in other words useless. You probably want to add in each step of n the variable ensemble to your lonlat data. So your code should be lonlat <- data.frame(cbind(lonlat, ensemble[n])).

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • This solution worked perfectly. I was wondering if you could expand on h being useless. I am a new r user and I dont fully understand some of the dynamics of objects in r. – Dylan Jul 12 '16 at 10:12
  • 1
    @Dylan each time the `for loop` executes it is 're-assigning' the object `h`. Therefore it is 'writing' over itself, hence why you are left with just the last output `n = 60` – amwill04 Jul 12 '16 at 10:43