Search code examples
rfor-loopxtsnames

set dimnames of an xts object with the names of certain elements in a list through loop


My question is only part of a function which I am coding.

I've got a list of data.frames (each with their own numeric and date columns) which have either weekly data or monthly data. I've defined 2 empty objects as "weekly" and "monthly" with which the for loop I have written goes through and finds out which element is weekly or monthly. Then, the loop categorises the each element as weekly/monthly and converts them into xts object.

library(xts)
weekly = NULL
monthly = NULL
for (i in 1:length(terms.list)) {
diff.days <- difftime(as.Date(terms.list[[i]][2,1]), as.Date(terms.list[[i]][1,1]))
if (diff.days < 10) {
  freq <- 52
  weekly = cbind(weekly, xts(terms.list[[i]][,2], order.by=terms.list[[i]][[1]], frequency=freq))
  } else {
  freq <- 12
  monthly = cbind(monthly, xts(terms.list[[i]][,2], order.by=terms.list[[i]][[1]], frequency=freq))
  }}

So I end up with two xts objects i.e. weekly and monthly. What I want now is to include in the for loop a line of code which picks out the colnames of the weekly defined terms (and monthly defined terms) and set those as the dimnames of each type of xts object respectively.

Something like:

dimnames(weekly)[[2]] <- names(terms.list[i])
dimnames(monthly)[[2]] <- names(terms.list[i])

Note that I want this to be in the for loop. I've tried it but it keeps on giving me the following errors:

Error in `colnames<-`(`*tmp*`, value = "jobs") : 
length of 'dimnames' [2] not equal to array extent 

"jobs" is one of the data.frame elements names.

Any assistance will be greatly appreciated.


Solution

  • I couldn't test this, because you didn't provide a reproducible example, but I think it should work. Basically, you need to construct a dimname list and set it in the xts constructor.

    library(xts)
    weekly <- NULL
    monthly <- NULL
    for (i in seq_along(terms.list)) {
      term <- terms.list[[i]]
      dimNames <- list(NULL, names(terms.list)[i])
      diff.days <- difftime(as.Date(term[2,1]), as.Date(term[1,1]))
      if (diff.days < 10) {
        freq <- 52
        weekly <- cbind(weekly, xts(term[,2], term[,1], freq, dimnames=dimNames))
      } else {
        freq <- 12
        monthly <- cbind(monthly, xts(term[,2], term[,1], freq, dimnames=dimNames))
      }
    }