List of list (or dictionary) in R

Viewed 44

I have a dataframe such as :

Groups Letters
G1   A
G1   A
G1   A
G1   A
G2   B
G2   B
G3   C
G3   C
G3   C
G4   A
G4   A
G5   C 

and I would like to parse the dataframe and create a list of list that I can interogate.

so in fact I would like to print the Groups for each name within this list such as :

list$A gives :

['G1','G4']

Does someone have an idea please ,

2 Answers

We could split the 'Groups' by 'Letters' on the unique dataset (assuming only two columns or else subset the selected columns), loop over the list and convert to nested list with as.list

lapply(with(unique(df1), split(Groups, Letters)), as.list)

-output

$A
$A[[1]]
[1] "G1"

$A[[2]]
[1] "G4"


$B
$B[[1]]
[1] "G2"


$C
$C[[1]]
[1] "G3"

$C[[2]]
[1] "G5"

If the OP wanted to create a string,

lapply(with(unique(df1), split(Groups, Letters)), 
      function(x) sprintf("[%s]", toString(sQuote(x, FALSE))))

-output

$A
[1] "['G1', 'G4']"

$B
[1] "['G2']"

$C
[1] "['G3', 'G5']"

Or probably, we can convert to JSON

library(jsonlite)
lapply(with(unique(df1), split(Groups, Letters)), function(x) toJSON(x))
$A
["G1","G4"] 

$B
["G2"] 

$C
["G3","G5"] 

data

df1 <- structure(list(Groups = c("G1", "G1", "G1", "G1", "G2", "G2", 
"G3", "G3", "G3", "G4", "G4", "G5"), Letters = c("A", "A", "A", 
"A", "B", "B", "C", "C", "C", "A", "A", "C")), 
class = "data.frame", row.names = c(NA, 
-12L))

A base R option using tapply could help

with(
  df,
  tapply(Groups, Letters, FUN = function(v) as.list(unique(v)))
)

which gives

$A
$A[[1]]
[1] "G1"

$A[[2]]
[1] "G4"


$B
$B[[1]]
[1] "G2"


$C
$C[[1]]
[1] "G3"

$C[[2]]
[1] "G5"
Related