如何使用 cbind 从列表中添加索引?



我的数据看起来像:

lis=list(NULL, NULL, structure(c("A", "30", "5"), .Dim = c(3L, 1L), .Dimnames = list(
c("Name", "M", "E") , "foo")), structure(c("B", "19", 
"9"), .Dim = c(3L, 1L), .Dimnames = list(c("Name", "M", "E"), "foo")))

合:

dat=do.call(cbind, lis)

在这里,我想用真实的对应关系替换foo(来自lis的索引(

期望输出 :

3      4 
Name "A"  "B" 
M    "30" "19"
E    "5"  "9" 

你可以做

as.data.frame(Filter(Negate(is.null), lis))
#     foo foo.1
#Name   A     B
#M     30    19
#E      5     9

说明:Filter(Negate(is.null), lis)在将条目转换为data.frame之前list中删除NULL条目。

要将列名替换为list条目的索引,请执行以下操作

setNames(
data.frame(Filter(Negate(is.null), lis)), 
which(sapply(lis, function(x) !is.null(x))))
#      3  4
#Name  A  B
#M    30 19
#E     5  9

如果我理解正确,您希望dat列的标签与索引中的lis匹配。但是,lis没有名称,只有显示在输出中的自动编号。您可以使用seq_along并过滤掉NULL元素来模拟这种情况:

colnames(dat) <- seq_along(lis)[!sapply(lis,is.null)]
dat
3    4   
Name "A"  "B" 
M    "30" "19"
E    "5"  "9"

如果lis确实有名称,您可以使用names(lis)而不是seq_along

最新更新