Reputation: 185
I have a data frame of colors and ids and want to turn them into a list with the colors as the name
and the id as the value
colors <- data.frame(color = c('Gold', 'Green', 'Red'), id = c('1','2','3'))
this is a small sample of the data frame, as there are a lot more rows.
I am trying to get the results to be equivalent as the output when you write:
colorlist <- list('Gold' = 1, 'Green' = 2, 'Red' = 3)
Upvotes: 0
Views: 1362
Reputation: 33743
setNames(as.list(colors$id), nm = colors$color)
$Gold
[1] "1"
$Green
[1] "2"
$Red
[1] "3"
Upvotes: 6
Reputation: 101
Try this. Looks a lot like MKBakker's solution. I added as.integer()
so the result as you described:
colorlist <- as.list(as.integer(colors$id))
names(colorlist) <- colors$color
Upvotes: 0
Reputation: 796
With split:
colorlist = split(x=colors$id, f=colors$color)
If levels are a problem just turn the id into character:
colorlist = split(x=as.character(colors$id), f=colors$color)
Upvotes: 5
Reputation: 947
Try:
colors <- data.frame(color = c('Red', 'Green', 'Gold'), id = c('1','2','3'))
colors_list <- as.list(as.character(colors$id))
names(colors_list) <- colors$color
colors_list
Upvotes: 2