1

I want an easy way to convert a data.table or tibble into a named list. I'm guessing it could be down with purrr, nest and split. This is for an options list in shiny.

There are similar question, but did not find any like this.

d <- tidyr::tribble(
  ~key,  ~value,
  'a',        1,
  'b',        2,
  'c',        3
)

result <- list(a = 1, b = 2, c = 3)
Harlan Nelson
  • 1,394
  • 1
  • 10
  • 22
  • You've seen [this](https://stackoverflow.com/q/60028873/5325862), [this](https://stackoverflow.com/q/19265172/5325862), and [this](https://stackoverflow.com/q/10432993/5325862)? – camille Feb 06 '20 at 21:00
  • @Camille I saw the last one, but the first two you mention would also work. – Harlan Nelson Feb 06 '20 at 21:06
  • After trying this with shiny selectInput, the with(df, setNames(Score, Words)) from @tmfmnk is what worked. So thanks for the comment. – Harlan Nelson Feb 06 '20 at 21:26

1 Answers1

4

One option is to deframe to create a named vector and then use as.list. to convert each element as a list element

library(tibble)
library(dplyr)
deframe(d) %>%
   as.list

Or in base R with split

with(d, split(value, key))
akrun
  • 874,273
  • 37
  • 540
  • 662