yaennu
yaennu

Reputation: 85

name columns of list element with same name

my code is like the following:

unemp <- c(1:10)
bsp_li <- list(c(1:10),c(11:20),c(21:30))
var_data_rep <- lapply(bsp_li, function(x) {cbind(as.numeric(x), as.numeric(unemp))} )
var_data_rep2 <- lapply(var_data_rep, function(x) {colnames(x) = c("rGDP", "U")} ) 

but it does not what i wanted. i would like to name always the two elements of the list var_data_rep with c("rGDP", "U"). but instead the values are overwritten by c("rGDP", "U") and becomes the sole elements of the list.. can anyone help? i need the same names because i want to estimate always the same model later.

Upvotes: 0

Views: 42

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146120

Easy fix: put the names in as the matrices are created:

var_data_rep <- lapply(bsp_li, function(x) {
  cbind(rGDP = as.numeric(x), U = as.numeric(unemp))
} )

More roundabout fix (why your attempt didn't work): functions return the last line. You want to return x, not colnames(x)

var_data_rep2 <- lapply(var_data_rep, function(x) {
  colnames(x) = c("rGDP", "U")
  return(x)
} ) 

Fancy fix: use the colnames<- function directly

var_data_rep3 = lapply(var_data_rep, `colnames<-`, c("rGDP", "U"))

Upvotes: 1

Related Questions