user3718600
user3718600

Reputation: 21

R matrix of lists

a=matrix(list(),2,2)
a[1,2]=list(2) ##works

a=matrix(list(),2,2)
a[1,2]=list(2,3) ##doesn't work

Error in a[1, 2] = list(2, 3) : number of items to replace is not a multiple of replacement length

That's the error message from the fourth line. If I try

x=list()
x=list(2,4)

it works, I don't see the difference as a[1,2] is a NULL list..

Thanks in advance.

Upvotes: 1

Views: 1269

Answers (1)

MichaelChirico
MichaelChirico

Reputation: 34703

When you replace with list(2), look at the output:

a=matrix(list(),2,2)
a[1,2]=list(2)    sapply(a, class)
# [1] "NULL"    "NULL"    "numeric" "NULL"  

That is, the [1,2] element is not a list.

list(2,3) can be coerced like that to a single element; as RichardScriven points out, the replacement must be length-1; the following works (a bit silly, I agree):

a = matrix(list( ), 2, 2)
a[1, 2] = list(list(2, 3))
a
#      [,1] [,2]  
# [1,] NULL List,2
# [2,] NULL NULL  

(just for reference, I figured this out by playing with dput, like so:)

#What happens if we declare 'a' as a
#  matrix of appropriately-sized lists to start with?
a <- matrix(replicate(4, vector("list", 2), simplify = FALSE), 2, 2)
a
#      [,1]   [,2]  
# [1,] List,2 List,2
# [2,] List,2 List,2
#
# can we replace now?
a[1,2] <- list(2,3)
# (same error; what IS 'a[1,2]' for this matrix?)
dput(a[1, 2])
# list(list(NULL, NULL))
# BINGO! we must replace 'a[1,2]' with a length-one list.

Upvotes: 1

Related Questions