简体   繁体   中英

How to save the output of for loop with nested while loop

For every value of latitude in a dataframe, I am calculating the daylength for each day (total 365 days) of the year. So, I have used for-loop to loop over the rows of dataframe and used while-loop to represent the day of year. But, I am not sure how to save the output.

for (i in 1:dim(df)[1]){
  j<-1
  while(j<=365){
  output<-daylength(lat=df$latitude[i],doy=j)
  j<-j+1
  # save output
  }
}

I am looking for the output to be in the following format: 输出

The simple method:

output <- data.frame(latitude = numeric(0),
                    matrix(numeric(0), ncol=365))
names(output) <- gsub("X", "day", names(my_df))


for (i in seq_len(nrow(df))){
  output[i, 1] <- df$latitude[i]
  j <- 1
  while(j <= 365){
    output[i, j + 1] <- daylength(lat = df$latitude[i], doy = j)
    j <- j + 1
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM