Here's a way using the switch
statement:
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 one downside of this is that you have to keep writing the category name (animal
, etc) for each item. It is syntactically more convenient to be able to define our categories as below (see the very similar question How do add a column in a data frame in R )
myMap <- list(animal = c('cow', 'pig'), bird = c('eagle', 'pigeon'))
and we want to somehow "invert" this mapping. I write 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 map as follows:
> invMap(myMap)
cow pig eagle pigeon
"animal" "animal" "bird" "bird"
And then it's easy to use this to add the type
column in 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