更改 data.table 中存储的嵌套列表的嵌套结构

Win*_*ied 1 r nested-lists data.table purrr

大纲

我试图在列表中找到等于给定总和的数字。我设法用简洁的语法计算所有数字组合及其总和。但我无法将生成的嵌套列表重组为不同类型的嵌套列表。

最小的例子

library(data.table)
library(purrr)

# raw data and basic operation
dt <- data.table(
  amount = c(2,5,9)
)[,
  `:=`(
    # nesting combinations into the data.table
    amount.set = map(1:.N,function(x) combn(amount,x)),
    sum = map(1:.N,function(x) colSums(combn(amount,x)))
  )
]

# desired structure of nested list
desired.output <- data.table(
  sum = c(2,5,9,7,11,14,16),
  amount.set = list(c(2),c(5),c(9),c(2,5),c(2,9),c(5,9),c(2,5,9))
)
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现 中的结构desired.output

r2e*_*ans 5

不确定我们是否需要中间计算,我们可以这样做:

data.table( id = 1:3, amount = c(2,5,9)
  )[, .(amount.set = unlist(lapply(1:.N, combn, x = amount, simplify = FALSE),
                            recursive = FALSE))
  ][, sum_ := sapply(amount.set, sum)][]
#    amount.set  sum_
#        <list> <num>
# 1:          2     2
# 2:          5     5
# 3:          9     9
# 4:        2,5     7
# 5:        2,9    11
# 6:        5,9    14
# 7:      2,5,9    16
Run Code Online (Sandbox Code Playgroud)

笔记:

  • lapply相当于map这里
  • 这与您的第一次尝试之间的第一个关键区别是我使用的是simplify=FALSE,这意味着每个组合(例如c(2,5))都在自己的列表中而不是矩阵中(其中每列都是一个组合);
  • 接下来,由于我们实际上有一个嵌套列表结构,因此我们需要一个非递归的unlist
  • 这和你的第二个关键区别是我们根据实际的组合列表计算列表上的总和,而不是计算combn(..)两次