mapvin vin
mapvin vin

Reputation: 81

Convert column data to list in R

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"

Upvotes: 0

Views: 41

Answers (2)

akrun
akrun

Reputation: 886938

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"

Upvotes: 1

Ma&#235;l
Ma&#235;l

Reputation: 51894

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"

Upvotes: 2

Related Questions