当您想将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
Run Code Online (Sandbox Code Playgroud)
关于为什么它不能与列表列表一起使用以及如何解决此问题的任何建议?谢谢
所以当你做
l <- list()
l[[index1]][[index2]] <- s
Run Code Online (Sandbox Code Playgroud)
问题是它l被初始化为一个列表,所以用 设置一个新的命名元素是有意义的l[[index1]],但 R 不知道存储在l[[index1]][[index2]]. 它可以是任何东西。它可能是一个函数,而函数不知道如何处理命名索引操作。例如
l <- list()
l[[index1]] <- mean
l[[index1]][[index2]] <- "character"
Run Code Online (Sandbox Code Playgroud)
但是在您的情况下,当您尝试从尚未初始化的列表中获取值时,您将获得NULL. 例如
l <- list()
l[[index1]]
# NULL
Run Code Online (Sandbox Code Playgroud)
当您尝试在 NULL 对象上设置命名原子值时,R 碰巧有特殊行为。观察
# NULL[["a"]] <- "character" is basically calling....
`[[<-`(NULL, "a", "character")
# a
# "character"
Run Code Online (Sandbox Code Playgroud)
请注意,我们在这里得到了一个命名向量。不是清单。这也适用于您的“工作”示例
l <- list()
l[[index1]][[index2]] <- "character"
class(l[[index1]][[index2]])
# [1] "character"
Run Code Online (Sandbox Code Playgroud)
另请注意,这与 S4 没有任何关系。如果我们也尝试设置一个更复杂的对象(如函数),也会发生同样的情况
l <- list()
l[[index1]][[index2]] <- mean
# Error in l[[index1]][[index2]] <- mean :
# invalid type/length (closure/0) in vector allocation
Run Code Online (Sandbox Code Playgroud)
在像 Perl 这样的语言中,您可以通过autovivification使用正确的索引语法“神奇地”使散列栩栩如生,但在 R 中则不然。如果您希望 alist()存在于 atl[[index1]]您将需要显式创建它。这将工作
l <- list()
l[[index1]] <- list()
l[[index1]][[index2]] <- s
Run Code Online (Sandbox Code Playgroud)
再次这是因为[[ ]]在 R 中有点模棱两可。它是一个通用索引函数,不专门用于列表。