Recoding a variable in R

Hi! I have a time variable which is coded "0, 1, 2 , 3," I want to recode this variable to be "--1.5, -0.5, 0.5, 1.5"

data1 <- data %>%
mutate(time = replace(time, time == 0, - 1.5 )) %>%
mutate(time = replace(time, time == 1, - 0.5 )) %>%
mutate(time = replace(time, time == 2, 0.5 )) %>%
mutate(time = replace(time, time == 3, 1.5 ))

i tried the following function, recode(data$time, "0" = - 1.5, "1" = -0.5, "2" = 0.5, "3" = 1.5)

But none of the functions would cooperate. Does anyone have any tips?

this looks like a good use case for dplyr::case_when

While this is not at all general, for the specific case you have how about

data$time <- data$time - 1.5

If the pattern is that you want to subtract 1.5 from each observation, the following simple approach also works to achieve that.

library(tidyverse)

time <- tibble(
  time = c(0, 1, 2, 3)
)

time %>% 
  mutate(time = time - 1.5)

#> # A tibble: 4 × 1
#>    time
#>   <dbl>
#> 1  -1.5
#> 2  -0.5
#> 3   0.5
#> 4   1.5

Thank you so much for all your answers. I ended up using the simple mutate() function which was proposed. But I'm going to take a look at the "case_when" function for future problems, im expecting them to not always be so elegant to solve.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.