简体   繁体   中英

R assign character values from list to unique groups in column of dataframe

I've found a lot of answers regarding true/false or ID's being assigned to unique values. Those are relatively straightforward. But I haven't found anything super helpful that assigns character values from a list to unique groups.

I have a list of class names that i use to specify border colors:

color_list <- list("red_point","blue_point","green_point","yellow_point","black_point")

And then I have a dataframe full of info:

items <- data.frame(
           category = c("Room","IceBreaker","Activity","Break","Activity","Break"),
           group_id=c(1,2,3,4,3,4),
           content = c("Big Room","Introductions","Red Rover","Lunch","Recess","Stretch"),
           length = c(480,60,120,90,30,10)
         )

What I want to do is add a new column for className that picks from color_list and assigns it to the unique groups, either by group_id or category.

The result would be something like:

items <- data.frame(
               category = c("Room","IceBreaker","Activity","Break","Activity","Break"),
               group_id=c(1,2,3,4,3,4),
               content = c("Big Room","Introductions","Red Rover","Lunch","Recess","Stretch"),
               length = c(480,60,120,90,30,10),
               className = 
               c("red_point","blue_point","green_point","yellow_point","green_point","yellow_point"
             )

I have been trying various match/unique/aggregate functions, but I'm striking out.

This approach makes use of the fact that group_id is a numeric variable that corresponds to the position in color_list:

items$className <- color_list[items$group_id]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM