【问题标题】:How to make a list of integer vectors in R如何在R中制作整数向量列表
【发布时间】:2011-04-27 21:42:16
【问题描述】:

基本问题:在 R 中,我如何创建一个列表,然后用向量元素填充它?

l <- list() 
l[1] <- c(1,2,3) 

这给出了错误“要替换的项目数不是替换长度的倍数”,因此 R 正在尝试解包向量。到目前为止,我发现唯一可行的方法是在制作列表时添加向量。

l <- list(c(1,2,3), c(4,5,6))

【问题讨论】:

    标签: r


    【解决方案1】:

    根据?"["(在“递归(类列表)对象”部分下):

     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.
    

    基本上,对于列表,[ 选择多个元素,因此替换必须是列表(而不是您示例中的向量)。以下是如何在列表中使用[ 的示例:

    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
    

    【讨论】:

      【解决方案2】:

      使用[[1]]

      l[[1]] <- c(1,2,3)
      l[[2]] <- 1:4
      

      等等。还记得预分配效率更高,所以如果你知道你的列表会有多长,请使用类似

      l <- vector(mode="list", length=N)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-22
        • 2021-12-25
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 2011-02-07
        相关资源
        最近更新 更多