Question

I got a bunch dynamically created regressions stored in some list called regressions. Now I´d like to rename their coefficients efficiently. What I have so far is this loop that works:

for (i in 1:length(params[,1])){
names(regressions[[i]]$coefficients)[pos] <- paste(params[i,1],".lag",params[i,2],sep="")
}

I've been trying for quite a while to get this done a little more generally with the help of a function, cause this not the only list of regressions I have. However I could not get anything else to work. Here a few other tries basically based on lapply:

 correctNames <- function(reglist,namevec,pos){
 names(reglist[[i]]$coefficients)[pos] <- as.character(namevec)
}

lapply(regressions,correctNames(reglist,namevec,pos),
reglist=regressions,namevec=params[,1],pos=2)

Another try was to write a function with a for loop which also works internally as print shows but does not assign the names globally (where the regressions list is stored).

correctNames <- function(reglist,pos,namevec){
for (i in 1:length(params[,1])){
names(reglist[[i]]$coefficients)[pos] <- paste(namevec,".lag",namevec,sep="")
}
#this test proves it's work inside the function... 
print(reglist[[10]]
}

Ah, gimme a break.

Was it helpful?

Solution

There's no "i" inside that first version of "correctNames" function; and you probably don't realize that you are not assigning it to "regressions", only to a copy of the regression object. Try instead:

correctNames <- function(reglist,namevec,pos){
  names(reglist$coefficients)[pos] <- as.character(namevec)
   return(reglist)                          }
newregs <- mapply(correctNames,  
                     reglist=regressions, 
                     namevec=as.character(params[,1]), 
                     MoreArgs= list( pos=2))

After seeing the note from Ramnath and noticing that the code did work but was giving flaky names for the "params" I looked at params and saw that it was a factor, and so changed the argument in the mapply call to as.character(params[,1]).

> newregs[1,1]
[[1]]
(Intercept)     log(M1) 
  -5.753758    2.178137 

OTHER TIPS

If this is a follow up to your earlier question, then here is what I would do

coefs = plyr::ldply(regressions, coef)
coefs = transform(coefs, reg_name = paste(x, '.lag', l, sep = ""))[,-c(1, 2)]
names(coefs) = c('intercept', 'reg_coef', 'reg_name')

This gives you

 intercept reg_coef     reg_name
1 -5.753758 2.178137 log(M1).lag0
2  7.356434 7.532603      rs.lag0
3  7.198149 8.993312      rl.lag0
4 -5.840754 2.193382 log(M1).lag1
5  7.366914 7.419599      rs.lag1
6  7.211223 8.879969      rl.lag1
7 -5.988306 2.220994 log(M1).lag4
8  7.395494 7.127231      rs.lag4
9  7.246161 8.582998      rl.lag4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top