coder_001
coder_001

Reputation: 27

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

Upvotes: 1

Views: 54

Answers (1)

Martin Gal
Martin Gal

Reputation: 16998

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

Upvotes: 1

Related Questions