Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group elements of a nested list?

Tags:

r

I would like to group the elements of a nested list in R, what is the best solution to do that ?

nest1 <- list(item1 = 1, item2 = "a")
nest2 <- list(item1 = 3, item2 = "b")
li <- list(nest1, nest2)
> li
[[1]]
[[1]]$item1
[1] 1

[[1]]$item2
[1] "a"


[[2]]
[[2]]$item1
[1] 3

[[2]]$item2
[1] "b"

What I'm trying to achieve is something like this :

[[1]]
[[1]]$item1
[[1]] 1 3

[[1]]$item2
[[1]] "a" "b"

I have try with lapply in several ways but it doesn't gives the expected result.

lapply(li, "[[", c("item1", "item2"))
like image 388
Florent Avatar asked Jan 26 '26 04:01

Florent


1 Answers

Using base:

as.list(do.call(rbind, lapply(li, data.frame, stringsAsFactors = FALSE)))

# $item1
# [1] 1 3
# 
# $item2
# [1] "a" "b"
like image 172
zx8754 Avatar answered Jan 28 '26 19:01

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!