我的数据看起来像:
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
。