Home > Mobile >  R: how to change attributes of list elements
R: how to change attributes of list elements

Time:05-05

I would like to change the class of all the items in a list from 'table' to 'matrix' Say the list of tables is

a <- letters[1:3]
t <- table(a, sample(a)) 
l <- list(t,t)

I use 'lapply' to change the class

l2 <- lapply(l, function(x) attributes(x)$class = 'matrix')
lapply(l2, class)

But every permutation I have tried changes the class to 'character'

CodePudding user response:

A slightly shorter / neater alternative is to use class<-

lapply(l, `class<-`, value = "matrix")
#> [[1]]
#>    
#> a   a b c
#>   a 1 0 0
#>   b 0 0 1
#>   c 0 1 0
#> 
#> [[2]]
#>    
#> a   a b c
#>   a 1 0 0
#>   b 0 0 1
#>   c 0 1 0

CodePudding user response:

The answer, as provided by Akrun, was to extend the function by enclosing it within curly brackets and adding a semi colon and 'x', i.e., returning the original object

CodePudding user response:

Here's another option:

lapply(l, function(x) matrix(x, ncol = ncol(x), dimnames = dimnames(x)))

# [[1]]
# 
# a   a b c
# a 0 0 1
# b 0 1 0
# c 1 0 0
# 
# [[2]]
# 
# a   a b c
# a 0 0 1
# b 0 1 0
# c 1 0 0
  • Related