【问题标题】:Referencing other items in a list before it is stored as an object在将列表存储为对象之前引用列表中的其他项目
【发布时间】:2022-01-23 04:27:45
【问题描述】:

我有一个列表,想创建一个新的列表条目d,方法是将现有列表条目绑定在一起,如下所示:

library(data.table)

## this works fine
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3))

example_list[["d"]] <- rbindlist(example_list[c("a", "b", "c")])

是否可以在创建原始列表的同时创建d?我想做这样的事情:

## this does not work
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3),
     "d" = rbindlist(.[c("a", "b", "c")]))

编辑:我需要明确引用以前的列表条目,因此这样的事情不起作用:

## ineligible
example_list <- list("a" = data.frame(x = 1),
     "b" = data.frame(x = 2),
     "c" = data.frame(x = 3),
     "d" = data.frame(x = 1) %>% 
       rbind(data.frame(x = 2)) %>% 
       rbind(data.frame(x = 3)))

【问题讨论】:

    标签: r


    【解决方案1】:

    我认为 base R 不支持这一点(也没有我能想到的没有类似 hack 的包)。我推断您希望这样做而不在主环境中留下单个帧(例如,ab),因此我们可以使用local 环境来做我们想做的事情。

    example_list <- local({
      a <- data.frame(x = 1)
      b <- data.frame(x = 2)
      c <- data.frame(x = 3)
      d <- rbindlist(list(a, b, c))
      list(a=a, b=b, c=c, d=d)
    })
    

    【讨论】:

      【解决方案2】:

      如果我们想使用%&gt;%,请将其包裹在{}

      library(dplyr)
      library(data.table)
      list("a" = data.frame(x = 1),
           "b" = data.frame(x = 2),
           "c" = data.frame(x = 3)) %>%
           {c(., d = list(rbindlist(.[c("a", "b", "c")])))}
      

      base R中,我们可以使用within.list从列表中获取数据

      within.list(list("a" = data.frame(x = 1),
           "b" = data.frame(x = 2),
           "c" = data.frame(x = 3)), d <- rbindlist(list(a, b, c)))
      

      -输出

      $a
        x
      1 1
      
      $b
        x
      1 2
      
      $c
        x
      1 3
      
      $d
         x
      1: 1
      2: 2
      3: 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-28
        • 1970-01-01
        • 2014-11-02
        • 2022-01-06
        相关资源
        最近更新 更多