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?
不确定我们是否需要中间计算,我们可以这样做:
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))都在自己的列表中而不是矩阵中(其中每列都是一个组合);unlistcombn(..)两次