ichabod ichabod - 14 days ago 8
R Question

Saving the output of a for loop to a data frame

I'm trying to apply a function to a netcdf data frame per row. Here's the reading part of the script.

library(ncdf4)
library(car)
library(forecast)
ncname <- "plus1"
ncfname <- paste(ncname,".nc", sep="")
dname <- "precip"
ncin <- nc_open(ncfname)
lon <- ncvar_get(ncin,"lon")
nlon <- dim(lon)
lat <- ncvar_get(ncin,"lat",verbose=F)
nlat <- dim(lat)
t <- ncvar_get(ncin,"time")
tunits <- ncatt_get(ncin,"time","units")
nt <- dim(t)
tmp_array <- ncvar_get(ncin,dname)
nc_close(ncin)
tmp_vec_long <- as.vector(tmp_array)
tmp_mat <- matrix(tmp_vec_long, nrow=nlon*nlat, ncol=nt)
lonlat <- as.matrix(expand.grid(lon,lat))
tmp_df02 <- data.frame(cbind(lonlat,tmp_mat))
tmp_df03<-na.omit(tmp_df02)

tmp_df03$lamb<-apply(tmp_df02[3:365],1,function(x)BoxCox.lambda(x,method="loglik",lower=-2,upper=2))


I want to use the values in the column tmp_df03$lamb and apply for each row of the data frame. For example (x should be the name of the data frame):

trans<-yjPower(x,tmp_df03$lamb,jacobian.adjusted=TRUE)


If I put this in a for loop:

d<-matrix(ncol=363,nrow=899)
for (i in 1:899){
trans[i]<-yjPower(as.numeric(tmp_df03[i,][3:365]),tmp_df03$lamb[i],jacobian.adjusted=TRUE)
d<-rbind(d,trans)
}


I encountered the following warning message.

Warning messages:

1: In trans[i] <- yjPower(as.numeric(tmp_df03[i, ][3:365]), tmp_df03$lamb[i], :


number of items to replace is not a multiple of replacement length

Question:


  1. How can I combine the output of the for loop and create a new data frame of the results?

  2. Can anyone suggest how any method of solving this?



I'll appreciate any help.
Many thanks,

Answer

using sapply() - I'm not much aware of yjPower() , so just giving you a hint!

vec <- sapply(seq_along(1:nrow(x)), function(i) yjPower(x[i,], tmp_df03$lamb[i], jacobian.adjusted = TRUE))

So above code will give a vector : to make this as a data.frame, use as.data.frame() on this vector.

If you want to join this to "x" then use cbind(x, as.data.frame(vec))

Comments