Reputation: 1029
My data looks like :
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")))
Combine :
dat=do.call(cbind, lis)
Here I want to replace foo
with the real correspondence (index from lis)
desired output :
3 4
Name "A" "B"
M "30" "19"
E "5" "9"
Upvotes: 2
Views: 520
Reputation: 66844
If I understand correctly you would like the label the columns of dat
to match how lis
in indexed. However, lis
has no names, just an automatic numbering that appears in output. You can simulate this using seq_along
and filtering out the NULL
elements:
colnames(dat) <- seq_along(lis)[!sapply(lis,is.null)]
dat
3 4
Name "A" "B"
M "30" "19"
E "5" "9"
If lis
did have names you can use names(lis)
instead of the seq_along
.
Upvotes: 2
Reputation: 50678
You can do
as.data.frame(Filter(Negate(is.null), lis))
# foo foo.1
#Name A B
#M 30 19
#E 5 9
Explanation: Filter(Negate(is.null), lis)
removes NULL
entries from your list
prior to converting entries to a data.frame
.
To replace column names with the index of the list
entry do
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
Upvotes: 2