当长度不同时用 sapply 替换循环来绑定列

问题描述 投票:0回答:1
这很愚蠢,但我不记得该怎么做。也许

do.call

cbind

在下面的列表

foo

 中,我想从每个 data.frames a、b 和 c 中获取 
y
 列,以在长度不同时使用 
bar
 值制作 
NA
。我想要的输出在
bar
中。理想情况下,我可以并排看到一个整洁的解决方案。

foo <- list( a = data.frame(x=1:2,y=c(5,4)), b = data.frame(x=1:5,y=c(3,1,4,5,2)), c = data.frame(x=1:3,y=c(8,9,0)) ) bar <- matrix(NA,ncol = 3, nrow = 5) for(i in 1:3){ tmp <- foo[[i]]$y bar[1:length(tmp),i] <- tmp }
    
r
1个回答
0
投票
可能您需要

merge

 通过 
Reduce
 获取数据帧

> unname(as.matrix(Reduce(\(x, y) merge(x, y, by = "x", all = TRUE), foo)[-1])) [,1] [,2] [,3] [1,] 5 3 8 [2,] 4 1 9 [3,] NA 4 0 [4,] NA 5 NA [5,] NA 2 NA
    
© www.soinside.com 2019 - 2024. All rights reserved.