NewbieDave
NewbieDave

Reputation: 1259

R lapply into data frame

I have a list contains list as elements. I want to convert all elements into data frame. Instead of using for loop. I used lapply function as follow:

myDF=lapply(mylist,FUN=as.data.frame)

However it's not converting.

class(myDF[1])

still returns list.

Any ideas? Thank you so much for your help,

Upvotes: 0

Views: 108

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99321

To look at the first element of the list as-is (i.e. not as a list) you will want to use [[ instead of [. So

class(myDF[[1]])

will tell you the class of the first list element in myDF.

Another way to see this is to look at the difference between myDF[1] and myDF[[1]]. myDF[1] returns the first element of the list as a single-element list, whereas myDF[[1]] returns the first element of the list as itself. See help(Extract) for more.

Upvotes: 1

Related Questions