简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM