提问人:Winfried 提问时间:10/18/2023 最后编辑:Winfried 更新时间:10/18/2023 访问量:65
更改存储在 data.table 中的嵌套列表的嵌套结构
Change nesting structure of a nested list stored in a data.table
问:
大纲
我正在尝试在列表中找到相当于给定总和的数字。我设法用简洁的语法计算了所有数字组合及其总和。但是我无法将生成的嵌套列表重构为不同类型的嵌套列表。
最小示例
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))
)
我怎样才能实现结构?desired.output
答:
5赞
r2evans
10/18/2023
#1
不确定我们是否需要中间计算,我们可以通过以下方式做到这一点:
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
笔记:
lapply
相当于这里map
- 这与您的第一次尝试之间的第一个关键区别是我使用的是,这意味着每个组合(例如,)都在自己的列表中,而不是矩阵(其中每列都是一个组合);
simplify=FALSE
c(2,5)
- 接下来,由于我们实际上有一个嵌套列表结构,我们需要一个非递归
unlist
- 这与你的第二个关键区别是,我们根据实际的组合列表计算列表中的总和,而不是计算两次
combn(..)
评论
1赞
Winfried
10/18/2023
我们绝对不需要任何中间计算,谢谢!
评论
id