R dplyr or purrr group_by to list of vectors

356 views Asked by At

I have data coming in from a database in key:value pairs, such as: year:2012 discipline:'Chemistry' subject:'General Chemistry' subject:'General, Organic, and Biochemistry'

incoming = tibble(field = c('year', 'discipline', 'subject', 'subject'), 
setting = c(2012, 'Chemistry', 'General Chemistry', 'General, Organic, and Biochemistry'))

I would like to group_by the key, and create a list with values = a vector of all values in that group, such as:

$year = 2012
$discipline = 'Chemistry'
$subject = c('General Chemistry', 'General, Organic, and Biochemistry')

I know I could paste() and collapse them into, say, a |-separated string, and then break that back apart... but I figure there's probably a tidy function that can do it in one step. Suggestions?

I'm thinking it will be something like this, but I'm not sure what to put at the end of the pipe:

processed = incoming %>%
   group_by(field) %>%
   awesome_listmaker_function()
1

There are 1 answers

0
Nathan Werth On BEST ANSWER
split(incoming$setting, incoming$field)
# $discipline
# [1] "Chemistry"
#
# $subject
# [1] "General Chemistry"                  "General, Organic, and Biochemistry"
#
# $year
# [1] "2012"

If you're receiving multiple groups at a time from the database, then it gets a little more complicated.