基本问题:在R中,我如何制作一个列表,然后用向量元素填充它?
l <- list()
l[1] <- c(1,2,3)
Run Code Online (Sandbox Code Playgroud)
这给出了错误"要替换的项目数不是替换长度的倍数",因此R试图解包向量.到目前为止,我发现工作的唯一方法是在制作列表时添加向量.
l <- list(c(1,2,3), c(4,5,6))
Run Code Online (Sandbox Code Playgroud)
Jos*_*ich 37
根据?"["(在"递归(类似列表)对象"部分):
Indexing by ‘[’ is similar to atomic vectors and selects a list of
the specified element(s).
Both ‘[[’ and ‘$’ select a single element of the list. The main
difference is that ‘$’ does not allow computed indices, whereas
‘[[’ does. ‘x$name’ is equivalent to ‘x[["name", exact =
FALSE]]’. Also, the partial matching behavior of ‘[[’ can be
controlled using the ‘exact’ argument.
Run Code Online (Sandbox Code Playgroud)
基本上,对于列表,[选择多个元素,因此替换必须是列表(不是示例中的向量).以下是如何[在列表中使用的示例:
l <- list(c(1,2,3), c(4,5,6))
l[1] <- list(1:2)
l[1:2] <- list(1:3,4:5)
Run Code Online (Sandbox Code Playgroud)
如果您只想替换一个元素,请[[改用.
l[[1]] <- 1:3
Run Code Online (Sandbox Code Playgroud)
Dir*_*tel 25
使用[[1]]如
l[[1]] <- c(1,2,3)
l[[2]] <- 1:4
Run Code Online (Sandbox Code Playgroud)
所以.还要记住,预分配效率要高得多,所以如果你知道你的列表有多长,那就用
l <- vector(mode="list", length=N)
Run Code Online (Sandbox Code Playgroud)