Search code examples
rarraysmatrixnames

how to give array elements names from a column of a dataframe in R


I have array and df below:

my.df <-  data.frame(cbind(c("a1","a2","a3","a4","a5","a6","a7","a8","a9","a10"), c(1:10)))
arr <- array(0, dim = c(2,3,10))

I want each element in my array gets its name from the corresponding row of my df. meaning for example, first element of array must be names a1, senod must be named a2 and so one.

    for( i in q:nrow(my.df)){
dimnames(arr[,,i])[[3]] <- my.df[i,1]
   

 }

this is what I m trying to do, which is not working. how can I get to this?


Solution

  • In the original dataset the dimnames attribute is NULL. So, we can create one with list specifying the first and second dimension names as NULL and the third from the first column of 'my.df'

    dimnames(arr) <- list(NULL, NULL, my.df[[1]])
    

    -output

    > arr
    , , a1
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a2
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a3
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a4
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a5
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a6
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a7
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a8
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a9
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0
    
    , , a10
    
         [,1] [,2] [,3]
    [1,]    0    0    0
    [2,]    0    0    0