Seth W. Bigelow
Seth W. Bigelow

Reputation: 59

R: how to change attributes of list elements

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'

Upvotes: 0

Views: 568

Answers (3)

AndrewGB
AndrewGB

Reputation: 16836

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

Upvotes: 0

Allan Cameron
Allan Cameron

Reputation: 173793

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

Upvotes: 3

Seth W. Bigelow
Seth W. Bigelow

Reputation: 59

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

Upvotes: 0

Related Questions