我正在尝试在列表中查找等于给定总和的数字。我设法用简洁的语法计算所有数字组合及其总和。但我无法将生成的嵌套列表重组为不同类型的嵌套列表。
library(data.table)
library(purrr)
# raw data and basic operation
dt <- data.table(
id = 1:3,
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))
)
如何实现
desired.output
中的结构?
不确定我们是否需要中间计算,我们可以这样做:
data.table( id = 1:3, amount = c(2,5,9)
)[, .(amount.set = do.call(c, lapply(seq(.N), combn, x = amount, simplify = 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