r语言 - 如何使用 lapply(seq_along()) 保留列表元素的名称?



我想用这段代码在每个lapply序列之后保留我的数据帧的名称。结果列表 (list2( 的所有数据帧名称都消失了。如何改进?谢谢。

list2<-lapply(seq_along(list1), function(i, USE.NAMES=T){
matrix_a%*%list1[[i]]
})

不要使用seq_along遍历列表,直接执行。

lapply(list1, function(x) matrix_a %*% x)

lapply使用传递给它的对象的名称。

假设您的list1类似于

list1 <- list(x = structure(c(1L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 
3L, 0L, 0L, 0L, 0L, 4L), .Dim = c(4L, 4L)), y = structure(c(1L, 
0L, 0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 3L, 0L, 0L, 0L, 0L, 4L), .Dim = c(4L, 4L)))

list1有名字

names(list1)
#[1] "x" "y"

seq_along(list1)没有名字。

names(seq_along(list1))
#NULL

因此,lapply的最终输出中不存在任何名称。


如果由于某种原因您必须传递索引,您可以稍后添加名称

setNames(lapply(seq_along(list1), function(i) matrix_a%*%list1[[i]]), names(list1))

我们也可以使用Map

Map(`%*%`, list(matrix_a), list1)

相关内容

最新更新