将S4对象保存在列表列表中

时间:2019-03-25 16:07:58

标签: r list s4

当您要将S4对象保存到列表列表中并且该元素先前尚未定义时,R给出以下消息错误。

"invalid type/length (S4/0) in vector allocation"

为什么使用简单列表而不使用列表列表?

请参阅以下代码和潜在的解决方法。 但是,我很确定还有一个更明显的解决方案。

# Creation of an S4 object
setClass("student", slots=list(name="character", age="numeric", GPA="numeric"))
s <- new("student",name="John", age=21, GPA=3.5)

# Indexes for the list
index1 <- "A"
index2 <- "a"

# Simple list (All of this works)
l <- list()
l[[index1]] <- s
l[[index1]] <- "character"
l[[index1]] <- 999


# List of list 
l <- list()
l[[index1]][[index2]] <- s          # will give an Error!!
l[[index1]][[index2]] <- "character" # still working
l[[index1]][[index2]] <- 999         # still working


# "Workarounds"
l <- list()
l[[index1]][[index2]] <- rep(999, length(slotNames(s))) #define the element with a length equal to the number of slots in the s4 object
l[[index1]][[index2]] <- s # this works now!


l[[index1]][[index2]] <- list(s) # This works too, but that's not the same result

关于为什么它不能与列表列表一起使用以及如何解决此问题的任何建议?谢谢

1 个答案:

答案 0 :(得分:3)

所以当你这样做

l <- list()
l[[index1]][[index2]] <- s

问题在于l被初始化为列表,因此使用l[[index1]]设置新的命名元素是有意义的,但是R不知道l[[index1]][[index2]]中存储了什么。可能是任何东西。它可能是一个函数,而函数不知道如何使用命名索引操作。例如

l <- list()
l[[index1]] <- mean
l[[index1]][[index2]] <- "character"

但是,在您的情况下,当您尝试从尚未初始化的列表中获取值时,将得到NULL。例如

l <- list()
l[[index1]]
# NULL
当您尝试在NULL对象上设置命名的原子值时,

R碰巧有特殊的行为。观察

# NULL[["a"]] <- "character" is basically calling....
`[[<-`(NULL, "a", "character")
#           a 
# "character" 

请注意,我们在这里得到一个命名向量。没有清单。您的“有效”示例也是如此

l <- list()
l[[index1]][[index2]] <- "character"
class(l[[index1]][[index2]])
# [1] "character"

还请注意,这与S4无关。如果我们尝试设置像函数一样的更复杂的对象,也会发生同样的情况

l <- list()
l[[index1]][[index2]] <- mean
# Error in l[[index1]][[index2]] <- mean : 
#   invalid type/length (closure/0) in vector allocation

在像Perl这样的语言中,您可以通过autovivification使用正确的索引语法来“神奇地”使哈希变得生动,但是在R中不是这样。如果您希望{{1}处有list() }},您需要明确创建它。这将起作用

l[[index1]]

同样是因为l <- list() l[[index1]] <- list() l[[index1]][[index2]] <- s 在R中有点含糊。这是一个通用索引函数,不专门用于列表。

相关问题