R 在列表中添加长度不等的数值向量以及基于索引的偏移量?

R 在列表中添加长度不等的数值向量以及基于索引的偏移量?,r,R,我有一个向量列表,如下所示: list_num 1 3 8 4 4 3 3 3 我目前的方法包括生成一个向量来容纳添加的结果,并迭代每个元素以添加它: # Find the length for each of the vectors in the list list_len <- unlist(lapply(list_num, function(x) { return(length(x))})) # Find how long will the vector to add the r

我有一个向量列表,如下所示:

list_num 1 3 8 4 4 3 3 3
我目前的方法包括生成一个向量来容纳添加的结果,并迭代每个元素以添加它:

# Find the length for each of the vectors in the list
list_len <- unlist(lapply(list_num, function(x) { return(length(x))}))

# Find how long will the vector to add the results have to be
list_len <- 1:length(list_num)+list_len

# Generate a vector to house the added results
list_len <- rep(0, max(list_len)-1) 

# Then iterate over each of the elements by index i 
for(i in 1:length(list_num)){

  # Add the vector at position i to the subset of our aggregated vector
  list_len[i:(i+length(list_num[[i]])-1)] <- list_len[i:(i+length(list_num[[i]])-1)] + list_num[[i]]
}

print(list_len)
>> 1 3 8 4 4 3 3 3
#查找列表中每个向量的长度

列表长度我们可以使用
lappy
添加偏移量0,使用
rep

out <- lapply(seq_along(list_num), function(n) c(rep(0, n-1), list_num[[n]]))
out

#[[1]]
#[1] 1 1 1 1 1

#[[2]]
#[1] 0 2 2

#[[3]]
#[1] 0 0 5

#[[4]]
#[1] 0 0 0 3 3 3 3 3

在C++中,代码的要求似乎并不难,因此这里有一个选项,使用<代码> Rcpp <代码>:

library(Rcpp)
cppFunction("NumericVector psumUnevenList(List a, int len) {
    NumericVector res(len), v;

    for (int i=0; i<a.length(); i++) {
        v = a[i];
        for (int j=0; j<v.length(); j++) {
            res[i+j] += v[j];
        }
    }

    return res;
}")
maxn <- max(seq_along(list_num) - 1L + lengths(list_num))
psumUnevenList(list_num, maxn)
#[1] 1 3 8 4 4 3 3 3
库(Rcpp)
cppFunction(“数字向量psumUnevenList(列表a,整数列){
数值向量res(len),v;
对于(int i=0;i基本R溶液(两步):

#在列表中以最长向量的长度存储标量值:

vec_list_max_length谢谢!这是朝着正确方向迈出的一步-但它不包括如何将它们加在一起,这仍然需要对每个元素进行迭代。我错过了这一部分。我已更新了答案以包含这一部分。感谢您这么做!我运行了两个测试,虽然比我当前的解决方案简洁得多,但它似乎更简洁s要慢得多,可能是因为添加了前导零(我想包括这一步来说明计算结果)。
rowSums(sapply(out, `[`, 1:max(lengths(out))), na.rm = TRUE)
#[1] 1 3 8 4 4 3 3 3
library(Rcpp)
cppFunction("NumericVector psumUnevenList(List a, int len) {
    NumericVector res(len), v;

    for (int i=0; i<a.length(); i++) {
        v = a[i];
        for (int j=0; j<v.length(); j++) {
            res[i+j] += v[j];
        }
    }

    return res;
}")
maxn <- max(seq_along(list_num) - 1L + lengths(list_num))
psumUnevenList(list_num, maxn)
#[1] 1 3 8 4 4 3 3 3
# Store a scalar valued at the length of longest vector in the list: 
vec_list_max_length <- max(lengths(vec_list))

# Set the length of each vector to be equal to the maximum length, rowbind the list
# together and get the sum of each row: 
rowSums(sapply(vec_list, function(x) {
  length(x) = vec_list_max_length
  return(replace(x, is.na(x), 0))
}))
vec_list <- list(c(1,1,1,1,1), c(0,2,2), c(0,0,5), c(0,0,0,3,3,3,3,3))