Can someone help me debug this code in R?

74 Views Asked by At

I have a weather data set for each experiment that is stored in a list called trimmed_data[[i]]. 1st data set from trimmed_data - original Degree Day values collected by weather stations

newlist <- list()
for(i in sequence(length(trimmed_data))){
  df2<-as.data.frame(trimmed_data[[i]])
  df2 <- transform(df2, 
                   obs.date = as.Date(as.character(df2$obs.date), format = "%Y-%m-%d"))
  month <- format(df2$obs.date, "%m")
  condition = isTRUE(month >= 1 & month < 9)
  which_row <- which(df2$obs.date == 12-31) 
  if(condition){
    last_DD <- df2[which_row,17]
    df2$DD.base.temp.0 <- df2$DD.base.temp.0 + last_DD
  }else{
    next
    }
  
  firstrow <- df2[1,]
  df2$DD.base.temp.0 <- df2$DD.base.temp.0 - firstrow$DD.base.temp.0
  newlist[[i]] <- df2
}

1st data set from newlist where first row is subtracted from every row

I need to obtain the value from row 109 of trimmed_data[1] which is 2593 to row 110 and onwards of newlist[1] and do the same thing for all of the data sets in the list.

Essentially, here is the breakdown of what I did.

  1. I converted the column obs.date from numeric to date type.
  2. Then I stored the month of each row into the vector "month". If the observation date is from January to August, I must add the the DD.base.temp.0 (or the Degree Days at 0 degree C base temperature) by December 31 of each year to these rows. Otherwise, no.
  3. Then I store the value of the first row of each dataset which is the sowing date of each experiment in a vector called first row.
  4. I subtract the value of first row to all the rows
  5. Then I compile everything in new_list.

The purpose of doing this is to reset the degree day at the sowing date to 0 and calculate the accumulation of Degree Days according to the cropping calendar. Weather stations start recording Degree Days (accumulated temperature needed by crops to grow) on the 1st of January and terminate on the 31st of December.

Unfortunately, my clock of code is not doing what it is meant to do. Do you know why it is not working? Do you have any suggestions?

I am analysing climate data for a good cause. Your help will be highly appreciated.

You can access the data files and script through this link: https://drive.google.com/drive/folders/1g_ivAe5MFfpNwif3h0DyHpOekat8fErx?usp=sharing

0

There are 0 best solutions below