0

I thought this would be easy but it is not working for. I am trying to follow this example to change the column names for each matrix in a list of matrices that I created:

Assign column names to list of dataframes

When I run the code below, I get a very weird return where it looks like I just set the name of each element in each matrix instead of just the column names.

#create a list of matrices containing random numbers
randoms<-lapply(1:1000, function(x) matrix(rnorm(1440), ncol=10))
trial<-lapply(randoms, setNames , nm = letters[1:10])

head(trial[[1]])
            [,1]        [,2]       [,3]        [,4]       [,5]       [,6]
[1,]  0.89032453  1.02459736  0.7141343 -0.47405630 -2.0719943 -1.5087669
[2,] -0.74866047  0.44086093 -1.7540066 -2.04227094 -0.4875453  1.4207707
[3,] -0.04565454 -1.52336294 -0.1941370 -1.36252338  1.7338307 -1.3536725
[4,]  0.13242099 -0.09157545 -0.6156536 -1.34546174 -0.3279853  0.9663668
[5,]  2.09173141  0.41592339  0.7422889 -0.05991624  0.5319697  0.6413341
[6,] -0.32129540  2.11206231  0.1722047 -0.54404820  1.2685971 -0.0784607
           [,7]       [,8]       [,9]      [,10]
[1,] -0.4849624 -1.2590439 -1.5066718 -0.6758746
[2,] -2.5010320 -2.3469163  0.5221117  0.9186142
[3,] -1.3763468 -0.5551194 -0.2304872 -1.6087508
[4,] -2.0282231 -0.1949064  0.9329241  1.0196325
[5,]  1.6429999  1.8176161 -0.6549447 -1.8833887
[6,]  1.0044023  1.5895154  0.3660308 -0.1883819

head(attr(trial[[1]], "names"))
[1] "a" "b" "c" "d" "e" "f"
Community
  • 1
  • 1
user3390169
  • 1,015
  • 1
  • 11
  • 34

1 Answers1

0

We can use a for loop

 for(i in seq_along(randoms)) {
        colnames(randoms[[i]]) <- letters[1:10]
 }
akrun
  • 874,273
  • 37
  • 540
  • 662