R列表矩阵

时间:2016-02-06 23:01:26

标签: r list matrix

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
  

[1,2] =列表(2,3)中的错误:要替换的项目数不是a   替换长度的倍数

这是来自第四行的错误消息。如果我试试

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

它有效,我看不出差异,a[1,2]NULL列表..

提前致谢。

1 个答案:

答案 0 :(得分:1)

当您使用list(2)替换时,请查看输出:

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

也就是说,[1,2]元素一个list

list(2,3)可以被强制转换为单个元素;正如RichardScriven指出的那样,替换必须是长度为1;以下作品(有点傻,我同意):

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

(仅供参考,我通过玩dput来解决这个问题,如下所示:)

#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.