基本问题:在R中,我如何制作一个列表,然后再使用 vector 元素填充它?
l <- list()
l[1] <- c(1,2,3)
这给出了错误“要替换的项目数不是替换长度的倍数”,因此R试图解压 vector 。到目前为止,我发现起作用的唯一方法是在创建列表时添加 vector 。
l <- list(c(1,2,3), c(4,5,6))
最佳答案
根据?"["
(在“递归(类似列表的)对象”部分下):
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.
基本上,对于列表,
[
选择多个元素,因此替换必须是列表(而不是示例中的 vector )。这是一个如何在列表上使用[
的示例:l <- list(c(1,2,3), c(4,5,6))
l[1] <- list(1:2)
l[1:2] <- list(1:3,4:5)
如果您只想替换一个元素,请改为使用
[[
。l[[1]] <- 1:3
关于r - 如何在R中列出整数向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5810969/