Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a data.frame/tibble to a list in a grouped manner

Tags:

list

r

I'd like to convert a data frame in a list with a specific format (minimal example ahead). For the following data frame, I' like to end up with a list of 5 elements which each have a list of 5 elements within themselves.

parameters = tidyr::expand(tibble(id=1:5, value = 1:5 * 2),id,value)

# A tibble: 6 x 2
     id value
  <int> <dbl>
1     1     2
2     1     4
3     1     6
4     1     8
5     1    10
6     2     2

result = base::split(parameters, list(parameters$id))
result = lapply(result, function(x) { x["id"] <- NULL; x })

so far it gets the id right (5 elements) but not the sub-elements within them. It gives for the first element

> a[1]
$`1`
# A tibble: 5 x 1
  value
  <dbl>
1     2
2     4
3     6
4     8
5    10

whereas I'd like to have it as in

> as.list(a$`1`$value)
[[1]]
[1] 2

[[2]]
[1] 4

[[3]]
[1] 6

[[4]]
[1] 8

[[5]]
[1] 10

such that the outcome looks something like this

[1]
  [[1]]
  [1] 2

   [[2]]
   [1] 4

   [[3]]
   [1] 6

   [[4]]
   [1] 8

   [[5]]
   [1] 10
[2]
  [[1]]
  [1] 2

   [[2]]
   [1] 4

   [[3]]
   [1] 6

   [[4]]
   [1] 8

   [[5]]
   [1] 10

Is there any elegant way to achieve this?

like image 759
MaHo Avatar asked Jan 19 '26 10:01

MaHo


1 Answers

Wrap as.list in lapply should do what you want:

lapply(with(parameters, split(value, id)), as.list)

$`1`
$`1`[[1]]
[1] 2

$`1`[[2]]
[1] 4

$`1`[[3]]
[1] 6

$`1`[[4]]
[1] 8

$`1`[[5]]
[1] 10


$`2`
$`2`[[1]]
[1] 2

$`2`[[2]]
[1] 4

$`2`[[3]]
[1] 6

$`2`[[4]]
[1] 8

$`2`[[5]]
[1] 10
like image 70
Psidom Avatar answered Jan 21 '26 02:01

Psidom



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!