Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two lists in a dataframe in R

Tags:

I have two lists with different structure:

listA <- list(c("a","b","c"), c("d","e"))
listB <- list(0.05, 0.5)

listA
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e"

listB
[[1]]
[1] 0.05

[[2]]
[1] 0.5

I have an idea of how to use looping to combine both lists in a dataframe that looks like the one below but I'm sure that there is a more efficient way of doing this.

data.frame(A = c("a","b","c","d","e"), B = c(rep(0.05,3), rep(0.5,2)))
  A    B
1 a 0.05
2 b 0.05
3 c 0.05
4 d 0.50
5 e 0.50
like image 635
Rami Al-Fahham Avatar asked Feb 20 '15 13:02

Rami Al-Fahham


People also ask

How do I combine lists into data frames in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function. Check out the Example given below to understand the Output of this command.

How do I join multiple lists in R?

lists is an R function developped combine/append two lists, with special attention to dimensions present in both. combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.

How do I combine list elements in R?

Combine lists in R Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.

How do I create a data frame from two lists?

Create pandas DataFrame from Multiple ListsUse column param and index param to provide column & row labels respectively to the DataFrame. Alternatively, you can also add column names to DataFrame and set the index using pandas. DataFrame. set_index() method.


2 Answers

This is another option:

do.call(rbind, Map(data.frame, A=listA, B=listB))

#   A    B
# 1 a 0.05
# 2 b 0.05
# 3 c 0.05
# 4 d 0.50
# 5 e 0.50
like image 185
Matthew Plourde Avatar answered Sep 17 '22 01:09

Matthew Plourde


Maybe there is a more elegant way that keeps the class numeric of list2's elements... But this one works as well

df <- do.call(rbind,mapply(cbind, listA, listB))
df <- as.data.frame(df, stringsAsFactors = FALSE)
df[,2] <- as.numeric(df[,2])

EDIT Way better is Matthew Plourde's solution using Map aka mapply(data.frame, A=listA, B=listB, SIMPLIFY = FALSE)

like image 45
Rentrop Avatar answered Sep 20 '22 01:09

Rentrop