我有以下列表,并希望将每个子列表的每个元素添加到第二个列表的每个元素,并将累积总和转发。有一点需要注意,每当该列表中删除的元素数量增加一个时,我就向前移动一个列表。计算非常耗时,并且想知道是否存在最后多个函数的可能公式以加速该函数。
DF3 <- list( c ( 12 ,35 ,90 ,33 ,51 ) , c ( 44 , 3 ,88 ,35 ,51 ) , c(12 ,16 ,6 ,10 ,3 ,12 ,2 ,6 ,9 ,4 ,4 ,51 ,13 ,22 ,51 ) , c( 44 ,3 ,37 ,51 ,35 ,51 ) , c( 12, 16 , 6 ,10 , 3 ,12 , 2 , 6 , 9 , 4 , 4 ,51 ,13 , 8 , 3 , 5 , 6 ,51 ) , c( 12 ,16, 6, 10, 3, 37, 51, 35, 51 ) , c( 12, 16, 16, 3, 37, 51, 35, 51 ))
DF3
[[1]]
12 35 90 33 51
[[2]]
44 3 88 35 51
[[3]]
12 16 6 10 3 12 2 6 9 4 4 51 13 22 51
[[4]]
44 3 37 51 35 51
[[5]]
12 16 6 10 3 12 2 6 9 4 4 51 13 8 3 5 6 51
[[6]]
12 16 6 10 3 37 51 35 51
[[7]]
12 16 16 3 37 51 35 51
# Obtain the list of elements to add to the prior list of elements sequentially.
fun <- function (x) tail ( DF3[[x]] , length ( DF3[[x]] ))
S <- lapply ( seq ( length ( DF3 ))[ 1 : ( max (length ( DF3 )))] , fun )[-1]
fun <- function (x) tail (S[[x]] , length( S[[x]])-x)
SS <- c( DF3[[1]][[1]], lapply ( seq ( length ( DF3 )-1), fun ))
# Every result element from previous sum will be added to next list of elements rolling one possition forward for each new list than in the prior list.
D1 <- ( SS[[1]] + SS[[2]] )
a <- seq(nrow(expand.grid(SS[[1]]+SS[[2]],SS[[3]])))
fun <- function (x) sum(expand.grid ( SS[[1]] + SS[[2]] , SS[[3]] )[,1][x], expand.grid ( SS[[1]] + SS[[2]] , SS[[3]] )[,2][x] )
D2 <- unlist(lapply (a , fun))
b <- seq(nrow(expand.grid(D2,SS[[4]])))
fun <- function (x) sum(expand.grid (expand.grid(D2,SS[[4]])[,1][x], expand.grid(expand.grid(D2,SS[[4]]))[,2][x] ))
D3 <- unlist(lapply (b , fun))
c <- seq(nrow(expand.grid(D3,SS[[5]])))
fun <- function (x) sum(expand.grid (expand.grid(D3,SS[[5]])[,1][x], expand.grid(expand.grid(D3,SS[[5]]))[,2][x] ))
D4 <- unlist(lapply (c , fun))
d <- seq(nrow(expand.grid(D4,SS[[6]])))
fun <- function (x) sum(expand.grid (expand.grid(D4,SS[[6]])[,1][x], expand.grid(expand.grid(D4,SS[[6]]))[,2][x] ))
D5 <- unlist(lapply (d , fun))
e <- seq(nrow(expand.grid(D5,SS[[7]])))
fun <- function (x) sum(expand.grid (expand.grid(D5,SS[[7]])[,1][x], expand.grid(expand.grid(D5,SS[[7]]))[,2][x] ))
D6 <- unlist(lapply (d , fun))
有没有办法以更简洁的方式写出最后一次表达,还有一种方法可以加速另一种表达,因为这非常慢。
修改
从最终结果D6(来自下面答案的cs)。我想找出每个DF3列表中的位置索引,当顺序缩进到221时。
# Taking the answer for the sake of time
f <- function(x, y) rep(x, length(y)) + rep(y, each = length(x))
cs <- SS[[1]]
for(i in 2:length(SS)) {
cs <- f(cs, SS[[i]])
}
# Those cs that add up to 221
which ( cs == 221 )
答案 0 :(得分:3)
Beyond the response from danas above you could use a fast expanding grid
library(data.table)
# data.table::CJ is a fast expand.grid
# get all value combinations
DT <- do.call(CJ, args = input_list) # get all combination
# See link - http://stackoverflow.com/questions/35418479/tracing-the-location-index-of-the-components-of-a-cumulative-sum-of-sequential-l
答案 1 :(得分:1)
expand.grid
是你的杀手。我的解决方案:
f <- function(x, y) rep(x, length(y)) + rep(y, each = length(x))
cs <- SS[[1]]
for(i in 2:length(SS)) {
cs <- f(cs, SS[[i]])
}