I am looking for a readable alternative to plyr::mapvalues
in data.table
.
For example, in plyr::mapvalues
, if I would like to change the values of carb
in mtcars
to type1, type2, type3
, I would do something like this:
library(tidyverse)
mtcars %>%
mutate(carb = plyr::mapvalues(
carb,
from = c("1", "2", "3", "4", "6", "8"),
to = c("type1", "type1", "type2", "type2", "type3", "type3")))
To get the same thing in data.table
, I would do it like this, which doesn't seem to be the conventional method:
library(data.table)
dt <- data.table(mtcars)
dt$carb <- as.character(dt$carb)
dt[which(carb %in% c("1", "2")),
carb := "type1"]
dt[which(carb %in% c("3", "4")),
carb := "type2"]
dt[which(carb %in% c("6", "8")),
carb := "type3"]
Is it possible to change all the values in one condition (dt[...]
)?