นี่คือวิธีการใช้switchคำสั่ง:
df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
                 stringsAsFactors = FALSE)
df$type <- sapply(df$name, switch, 
                  cow = 'animal', 
                  pig = 'animal', 
                  eagle = 'bird', 
                  pigeon = 'bird')
> df
    name   type
1    cow animal
2    pig animal
3  eagle   bird
4 pigeon   bird
ข้อเสียอย่างหนึ่งคือคุณต้องเขียนชื่อหมวดหมู่ ( animalฯลฯ ) สำหรับแต่ละรายการ มันสะดวกกว่าในเชิงไวยากรณ์ที่จะสามารถกำหนดหมวดหมู่ของเราได้ดังต่อไปนี้ (ดูคำถามที่คล้ายกันมากจะเพิ่มคอลัมน์ในกรอบข้อมูลใน R ได้อย่างไร )
myMap <- list(animal = c('cow', 'pig'), bird = c('eagle', 'pigeon'))
และเราต้องการ "กลับด้าน" การแมปนี้ ฉันเขียนฟังก์ชัน invMap ของตัวเอง:
invMap <- function(map) {
  items <- as.character( unlist(map) )
  nams <- unlist(Map(rep, names(map), sapply(map, length)))
  names(nams) <- items
  nams
}
จากนั้นกลับแผนที่ด้านบนดังนี้:
> invMap(myMap)
     cow      pig    eagle   pigeon 
"animal" "animal"   "bird"   "bird" 
จากนั้นใช้สิ่งนี้เพื่อเพิ่มtypeคอลัมน์ใน data-frame:
df <- transform(df, type = invMap(myMap)[name])
> df
    name   type
1    cow animal
2    pig animal
3  eagle   bird
4 pigeon   bird
     
              
dput()b) คุณต้องการโซลูชันในฐาน R, dplyr, data.table, tidyverse ... ?