Reputation: 505
I currently have the below list and am trying to develop a data frame from the results. Essentially, I would like to take the first list and add it to a new data frame, creating columns with variable names, and storing the results in the first row. Then move to the next list and create a new y
column so that any variables with y
results would be added to that list.
list
[[1]]
x xy
1.000365 1.000365
[[2]]
x y
1.007184 1.007184
[[3]]
x y
1.020803 1.020803
[[4]]
NA
Is this possible to do? I've been trying to figure out how a for loop
or lapply
might work in this scenario but am unsure.
Thanks.
Upvotes: 0
Views: 79
Reputation: 39717
You can use [
in lappy
on unique
names
of the vectors:
i <- unique(unlist(lapply(x, names)))
setNames(as.data.frame(do.call(rbind, lapply(x, `[`, i))), i)
# x xy y
#1 1.000365 1.000365 NA
#2 1.007184 NA 1.007184
#3 1.020803 NA 1.020803
#4 NA NA NA
Data:
x <- list(c(x=1.000365, xy=1.000365), c(x=1.007184, y=1.007184),
c(x=1.020803, y=1.020803), NA)
Upvotes: 1
Reputation: 5429
lapply, or even better bind_rows would be good for this:
library(dplyr)
d <- bind_rows( your.list )
Note, I assume the xy
name of the 2nd element of the first list entry is a typo?
Upvotes: 1