0

I am recoding a variable in R with the case_when function, changing only some of the values according to a set of rules, but when I print the new variable, the values I didn't include in the case_when function also change.

The variable I want to recode is a mixed variable that has character and numeric values. I am using the case_when function to transform the character values into numeric. The case is that when I print the new variable (expecting to get the old numeric values plus the new numeric values), the old numeric values also have changed.

Below there is the code I'm using..

pobgit_p %>% 
  mutate(P57_2_num = case_when(
    P57_2 == "No" ~ 0,
    P57_2 == "NS" ~ 0,
    P57_2 == "NC" ~ 0,
  ))

I don't get what I am doing wrong.

Many thanks in advance :)

anais_xis
  • 33
  • 3

1 Answers1

0

Perhaps adding TRUE ~ as.numeric(P57_2_num) will help?

Please take a moment to learn how to provide a proper reproducible example. Doing so will help us provide solutions that more accurately reflect your data. Also, more experienced users might be able to catch other potential problems that you may not be aware of.

library(tibble)
library(dplyr)

pobgit_p <- tibble(
  P57_2_num = c("No",
                "NS",
                "NC",
                10,
                20,
                100)
) 

pobgit_p %>% 
  mutate(P57_2_num = case_when(
      P57_2_num == "No" ~ 0,
      P57_2_num == "NS" ~ 0,
      P57_2_num == "NC" ~ 0,
      TRUE ~ as.numeric(P57_2_num)
  ))

Output:


# A tibble: 6 x 1
  P57_2_num
      <dbl>
1         0
2         0
3         0
4        10
5        20
6       100

Created on 2020-11-13 by the reprex package (v0.3.0)

Original table:

# A tibble: 6 x 1
  P57_2_num
  <chr>    
1 No       
2 NS       
3 NC       
4 10       
5 20       
6 100 
Eric
  • 2,699
  • 5
  • 17