0
votes

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
1
Change the last bit to mutate(c = ifelse(c == 3, 300, c) - Phil
@Phil I can't - in real life I have to recode more than 1 value, in other words I want to recode 3 into something and 1 into something, but not the rest. - user3245256
case_when() is specifically designed for this. - Phil
mutate(c = case_when(c == 3 ~ 300, c == 1 ~ 'something', TRUE ~c)) - Axeman
@Axeman I tried: x %>% mutate(c = a*b) %>% mutate(c = case_when(c == 3 ~ 300, TRUE ~c)), but it gives an error: Evaluation error: must be type double, not integer - user3245256

1 Answers

2
votes

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