我有一个清单,看起来是这样的:
[[1]]
[1] -3
[[2]]
[1] 0 0
[[3]]
[1] 6 -36 54我想从这里创建一个向量,看上去
3 -36 54要做到这一点,我考虑在元素的末尾添加零,这足以使元素大小相等,并使用
Reduce('+',....)将元素粘贴在一起。但是,我不想添加过多的零。上面提到的列表没有必要列出我想要的列表。我有多个名单。最后,我的问题是:是否有方法从列表中检索元素的最大长度?
发布于 2018-12-12 11:01:20
我们用length获取list各个元素的lengths,然后用max获取它的max值,创建逻辑索引和子集list。
i1 <- max(lengths(lst))
i2 <- lengths(lst)== i1
lst[i2]假设OP想要像文章中所描述的向量
f1 <- function(listA, i = 1) {
i1 <- max(lengths(listA))
listB <- lapply(listA, `length<-`, i1)
Reduce(`+`, lapply(listB, function(x) replace(x, is.na(x), 0)))
}
f1(lst)
#[1] 3 -36 54如果我们在matrix中需要它,可以用stri_list2matrix完成它,用rowSums获取sum
library(stringi)
out <- stri_list2matrix(lst)
class(out) <- 'numeric'
rowSums(out, na.rm = TRUE)
#[1] 3 -36 54数据
lst <- list(-3, c(0, 0), c(6, -36, 54))发布于 2018-12-12 11:17:12
您可以将列表展开为填充NA的矩阵,并在其上使用rowSums:
# Data
foo <- list(-3, c(0, 0), c(6, -36, 54))
rowSums(sapply(foo, "[", seq_len(max(lengths(foo)))), na.rm = TRUE)
[1] 3 -36 54sapply生成的矩阵使用列表中最长向量的长度(seq_len(max(lengths(foo)))):
[,1] [,2] [,3]
[1,] -3 0 6
[2,] NA 0 -36
[3,] NA NA 54发布于 2018-12-12 11:33:18
带有助手函数的Reduce()解决方案:
`%+na%` <- function(x, y) {
# Originally from: # https://stackoverflow.com/a/13106770/4552295
ifelse(is.na(x), y, ifelse(is.na(y), x, x + y))
}
n <- max(lengths(lst))
Reduce("%+na%", lapply(lst, "[", 1:n))
[1] 3 -36 54https://stackoverflow.com/questions/53741561
复制相似问题