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
  • In order for us to help you, please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For example, to produce a minimal data set, you can use `head()`, `subset()`, or the indices. Then use `dput()` to give us something that can be put in R immediately. Also, please make sure you know what to do [when someone answers your question](https://stackoverflow.com/help/someone-answers). More info can be found at Stack Overflow's [help center](https://stackoverflow.com/help). Thank you! – iamericfletcher Nov 13 '20 at 17:21

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 
iamericfletcher
  • 2,529
  • 6
  • 17