Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Alternative to plyr::mapvalues in data.table

$
0
0

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[...])?


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>