Convert the list of characters into a data frame in r

advertisements

suppose I have the following list:

a=list()
a[1]<-c("1")
a[2]<-c("3")
a[[1]][2]<-c("a")
a[[2]][2]<-c("b")

List of 2
 $ : chr [1:2] "1" "a"
 $ : chr [1:2] "3" "b"

[[1]]
[1] "1" "a"

[[2]]
[1] "3" "b"

How can I convert that list into a data frame like this? This is how the info would looks like:

table<-data.frame(col1=c("1a","3b")) 

 col1
  1a
  3b

'data.frame':   2 obs. of  1 variable:
 $ col1: Factor w/ 2 levels "1a","3b": 1 2


You can use , do.call as well however, I do feel the answer in the comment is better than this:

df <- setNames(data.frame(do.call("paste0",data.frame(do.call("rbind",a)))),"col1")

You can always read about do.call from documentation:

do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

Output:

> df
  col1
1   1a
2   3b

> str(df)
'data.frame':   2 obs. of  1 variable:
 $ col1: Factor w/ 2 levels "1a","3b": 1 2