0

I got a dataframe like this

input

    ID   RE
    am_A re456
    am_A re4
    am_B re20
    am_C re47 
    am_B re456
    am_C re12

And I would like to convert this two column in one list like this :

output :

$`am_A`
[1] "re456" "re4"

$`am_B`
[1] "re20" "re456"

$`am_C`
[1] "re47" "re12"

3 Answers 3

1

Simply use split from base R:

split(dat$RE, dat$ID)

# $am_A
# [1] "re456" "re4"  
# 
# $am_B
# [1] "re20"  "re456"
# 
# $am_C
# [1] "re47" "re12"

Data:

dat <- structure(
  list(
    ID = c("am_A", "am_A", "am_B", "am_C", "am_B", "am_C"),
    RE = c("re456", "re4", "re20", "re47", "re456", "re12")
    ),
  class = "data.frame", row.names = c(NA,-6L)
)
0

dlply was made for this:

your.data %>% dlply( "ID", `[[`, "RE" )

Output:

$am_A
[1] "re456" "re4"  

$am_B
[1] "re20"  "re456"

$am_C
[1] "re47" "re12"

attr(,"split_type")
[1] "data.frame"
attr(,"split_labels")
    ID
1 am_A
2 am_B
3 am_C

If you don't want those extra attributes there, you can just pipe to c:

data %>% dlply( "ID", `[[`, "RE" ) %>% c
0

Try using pivot_wider, then unnest-ing the columns, and finally as.list to get a list.

library(tidyverse)

my_df <- tibble::tribble(
      ~ID, ~RE,
  "am_A","re456",
    "am_A","re4",
   "am_B","re20",
   "am_C","re47",
  "am_B","re456",
   "am_C","re12"
  )

my_df %>% 
  pivot_wider(names_from = ID, 
              values_from = RE, 
              values_fn = list) %>%  #to suppress a warning
  unnest(cols = names(.)) %>%        # unnest needs column names now
  as.list()
#> $am_A
#> [1] "re456" "re4"  
#> 
#> $am_B
#> [1] "re20"  "re456"
#> 
#> $am_C
#> [1] "re47" "re12"

Created on 2021-04-13 by the reprex package (v0.3.0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.