matlabcat
matlabcat

Reputation: 192

How do I match the number of days in a month to a list level and carry out arithmetic in R

I need to multiply the data in each level of a list (each of which correspond to a month) by the number of days in that month.

My list looks like this:

tmintest=array(0.11:100.4, c(1,256,512))
l <- lapply(1:12, function(i) {
#create the list
Variable <- list(varName = c("tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin"),level = c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
Data = tmintest
xyCoords <- list(x = seq(-40.37,64.37,length.out=420), y = seq(25.37,72.37,length.out=189))
Dates <- list(start = seq(as.Date("2012-01-01"), as.Date("2015-12-31"), by="days"), end=seq(as.Date("2012-01-01"), as.Date("2015-12-31"), by="days"))
Delta <- list(Variable = Variable,Data=Data, xyCoords=xyCoords,Dates=Dates)
})

I think I need to define the months and the number of days per month:

  mth <- c(1:12)

#Number of days by month

  ndays <- c(31,28,31,30,31,30,31,31,30,31,30,31)

Then make a dataframe with this information

mthdays<- as.data.frame(cbind(mth, ndays))

Then I need to match the number in each level of the list (for example January is l[[1]])to my ndays (via the mth) and multiply the Data in that level (l[[1]][["Data"]]) by ndays. I think using which might be useful (matching the number at each level of my list to the mth in my dataframe, but I'm unsure as to the best way to do it.

Upvotes: 1

Views: 83

Answers (1)

akrun
akrun

Reputation: 887621

We can use a for loop. As the length of list is 12 and is in the same order as the ndays, just loop over the sequence of l, extract the list element with position index, get the inner named list element 'Data' (using $) and multiply with the corresponding 'ndays' element

for(i in seq_along(l)) l[[i]]$Data <- l[[i]]$Data * ndays[i]

Upvotes: 2

Related Questions