ichabod ichabod - 9 months ago 55
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.

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)
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))


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):


If I put this in a for loop:

for (i in 1:899){

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


  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 Source

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))