How can I convert this list to a dataframe with same names in R?

Viewed 151

I have the following data in R:

list0 <- list(ff = 45,gg = 23)
list1 <- list(a = 2, b=list0)
LIST <- list(mylist = list1)

I want to convert this list to a dataframe and get an output dataframe as follows, which has the following column header naming conventions:

  a b.ff b.gg
1 2   45   23

any help is appreciated.

3 Answers

The LIST step was unnecessary:

> data.frame(list1)
  a b.ff b.gg
1 2   45   23
vec <- unlist(LIST)
names(vec) <- sub("mylist.", "", names(vec))
dt <- data.frame(as.list(vec))

dt
  a b.ff b.gg
1 2   45   23

You can also use do.call with data.frame to construct the data.frame and include unname to drop the name of the first list level.

mydf <-do.call(data.frame, unname(LIST))

mydf
  a b.ff b.gg
1 2   45   23

Make sure that the object has the desired structure.

str(mydf)
'data.frame':   1 obs. of  3 variables:
 $ a   : num 2
 $ b.ff: num 45
 $ b.gg: num 23
Related