Search code examples
rdplyrrecode

using dplyr's recode to recode only some numeric values in a column


it's important to me to recode using pipes, so, please don't offer base R solutions, please.

Also important: I have both libraries activated: car and tidyverse.

So, I have a data frame x. I want to produce a new column c and then recode ONLY the value of 3 in it as 300. The following is working when I want to replace with an integer, but what if I need to recode into a float?

Thank you!

library(car)
library(tidyverse)
x <- data.frame(a = 1:3, b = 3:1)
x %>% mutate(c = a*b) %>% mutate(c = dplyr::recode(c, `3` = 300L)) # Works
x %>% mutate(c = a*b) %>% mutate(c = dplyr::recode(c, `3` = 0.333)) # Doesn't work

Solution

  • Is this what you're looking for? If you change c to double you can then use double precision (decimals). Per @Axeman and @Jay's comments, it maintiains the type across the variable.

    x %>% mutate(c = a*b) %>% mutate(c = dplyr::recode(as.double(c), `3` = 0.333))
    
      a b     c
    1 1 3 0.333
    2 2 2 4.000
    3 3 1 0.333