Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to dataframe in R and add column with names of sub-lists

Tags:

list

dataframe

r

List l has three strings that are named one, two, and three, respectively. I want to convert l to a dataframe, and I need an additional column with the names in n.

l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")

I can do it using a loop, but I'm sure there are more efficient ways of doing this.

out <- NULL
for (i in 1:length(n)){
  step <- rep(n[i], length(l[[i]]))
  out <- c(out, step)}

df <- as.data.frame(unlist(l))
df$n <- out
df

#  unlist(l)     n
#1         a   one
#2         b   one
#3         c   two
#4         d   two
#5         e   two
#6         e three
like image 210
milan Avatar asked Aug 06 '16 00:08

milan


People also ask

How do I convert a nested list to a DataFrame in R?

frame() converts the nested list to an R DataFrame by taking do. call() function as a parameter. So each list inside a nested list will be a column in a DataFrame. So the column names in the DataFrame will be nested list names.

How do I convert a list to a DataFrame in R?

To convert List to Data Frame in R, call as. data. frame() function and pass the list as argument to it.

How do you append a list as a column in a DataFrame in R?

Append a Column to Data Frame You need to use the symbol $ to append dataframe R variable and add a column to a dataframe in R.


1 Answers

Using base R, you can essentially do it in two lines.

l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")

#Create an appropriately sized vector of names
nameVector <- unlist(mapply(function(x,y){ rep(y, length(x)) }, l, n))

#Create the result
resultDF <- cbind.data.frame(unlist(l), nameVector)


> resultDF
  unlist(l) nameVector
1         a        one
2         b        one
3         c        two
4         d        two
5         e        two
6         e      three
like image 101
user1357015 Avatar answered Oct 27 '22 08:10

user1357015