The switch method is used here:
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
The only drawback to this is that you must continue to write the category name ( animal , etc.) for each item. It is syntactically more convenient to define our categories as shown below (see a very similar question How to add a column to a data frame in R )
myMap <- list(animal = c('cow', 'pig'), bird = c('eagle', 'pigeon'))
and we want to somehow "invert" this mapping. I am writing my own invMap function:
invMap <- function(map) { items <- as.character( unlist(map) ) nams <- unlist(Map(rep, names(map), sapply(map, length))) names(nams) <- items nams }
and then invert the above mapping as follows:
> invMap(myMap) cow pig eagle pigeon "animal" "animal" "bird" "bird"
And then it's easy to use this to add a type column to the data frame:
df <- transform(df, type = invMap(myMap)[name]) > df name type 1 cow animal 2 pig animal 3 eagle bird 4 pigeon bird
Prasad Chalasani Jan 07 2018-11-11T00: 00Z
source share