简体   繁体   中英

Add Unique Names from List to Create Columns in Dataframe

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.

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM