Below is the nested list that is framed manually. Similar to this, can we make a nested list for dataframe columns like shown below
nested_list = list(`East Coast` = list("NY", "NJ", "CT"),
`West Coast` = list("WA", "OR", "CA"),
`Midwest` = list("MN", "WI", "IA"))
Example
asd <- data.frame(Cat1 = c("A", "A", "B", "B"), Cat2 = c("x","y", "x1", "y1"))
Expected output
$`A`
$`A`[[1]]
[1] "x"
$`A`[[2]]
[1] "y"
$`B`
$`B`[[1]]
[1] "x1"
$`B`[[2]]
[1] "y1"
CodePudding user response:
You can do:
lapply(split(asd[, -1], asd$Cat1), as.list)
$A
$A[[1]]
[1] "x"
$A[[2]]
[1] "y"
$B
$B[[1]]
[1] "x1"
$B[[2]]
[1] "y1"
CodePudding user response:
Or convert to list
first and then split
with(asd, split(as.list(Cat2), Cat1))
$A
$A[[1]]
[1] "x"
$A[[2]]
[1] "y"
$B
$B[[1]]
[1] "x1"
$B[[2]]
[1] "y1"