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
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.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With