user3012926
user3012926

Reputation: 127

Converting dataframe to structured list

In the following .RData file:

https://www.dropbox.com/s/ct6ttye8mmci22v/Test_Data_Colours.RData?dl=0

I'm looking to convert the dataframe b into a structured, dictionary list (an example of which is shown in my_colour[["CellType"]]).

I've tried:

xy.list <- setNames(split(b, seq(nrow(b))), rownames(b))

But it does not give the desired result, and I am not sure how to do this. Is there a simple and/or short way of achieving the conversion?

Upvotes: 0

Views: 36

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can do

setNames(b$Colour, b$CellType)
#>       Macrophages                DC         Microglia      B cells, pro 
#>         "#E9C825"         "#E77800"         "#E3B60B"         "#EE3900" 
#>                NA       Neutrophils         Monocytes        Mast cells 
#>         "#54A6BA"         "#E39700"         "#7EB8BC"         "#6EB2C2" 
#> Endothelial cells         Basophils           B cells        Stem cells 
#>         "#E7C21C"         "#E1B002"         "#3B9AB2"         "#AEC07B" 
#>           T cells               NKT               ILC               Tgd 
#>         "#E5BC13"         "#61ACBE"         "#96BC9C"         "#C6C55A" 
#>          NK cells  Epithelial cells       Fibroblasts     Stromal cells 
#>         "#EA5800"         "#47A0B6"         "#F21A00"         "#DEC93A" 

In R this is called a named character vector rather than a dictionary list.

class(my_colour[["CellType"]])
#> [1] "character"

attributes(my_colour[["CellType"]])
#> $names
#>  [1] "Macrophages"       "DC"                "Microglia"         "B cells, pro"     
#>  [5] "NA"                "Neutrophils"       "Monocytes"         "Mast cells"       
#>  [9] "Endothelial cells" "Basophils"         "B cells"           "Stem cells"       
#> [13] "T cells"           "NKT"               "ILC"               "Tgd"              
#> [17] "NK cells"          "Epithelial cells"  "Fibroblasts"       "Stromal cells" 

Upvotes: 1

Related Questions