Reputation: 397
Let's say I have a dataframe:
a <- c('zz','yy','xx','qq','pp')
b <- c('1','2','2','3','1')
ab <- data.frame(a,b)
This gives:
a b
1 zz 1
2 yy 2
3 xx 2
4 qq 3
5 pp 1
I would like to turn this into a dictionary/nested list in R. I can imagine in python, the result would look like this:
ab_dict = {'1':["zz","pp"],'2':["yy","xx"],'3':["qq]}
How can this be achieved in R? I would like the result to be iterable in a for loop afterwards.
I couldn't find any solution for this on stackoverflow so I apologise if something similar has been asked!
Upvotes: 1
Views: 190
Reputation: 887841
An option would be to split
the 'ab' column by 'b' and use toJSON
from jsonlite
library(jsonlite)
toJSON(split(as.character(ab$a), ab$b))
#{"1":["zz","pp"],"2":["yy","xx"],"3":["qq"]}
Upvotes: 1