strengejacke / sjmisc

Data transformation and utility functions for R

Home Page:https://strengejacke.github.io/sjmisc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

rec into the same variable

andresimi opened this issue · comments

Hi, the standard option in rec is recoding into a new variable. Is there a way for doing this into the same variable? When I use suffix="" it creates new variables with numbers as suffix.

Yes, "overwriting" existing variables is not directly possible (for safety reasons). The current way to do this is to return only the recoded variables (w/o suffix) and replace the old variables, using add_colums():

library(sjmisc)
dat <- data.frame(
  a = c(1, 1, 1, 2, 2, 2),
  b = c(1, 1, 1, 3, 3, 3),
  c = c(1, 1, 1, 4, 4, 4)
)

dat
#>   a b c
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 3 4
#> 5 2 3 4
#> 6 2 3 4

dat %>%
  rec(a, b, rec = "1=5;else=copy", append = F, suffix = "") %>% 
  add_columns(dat)
#>   a b c
#> 1 5 5 1
#> 2 5 5 1
#> 3 5 5 1
#> 4 2 3 4
#> 5 2 3 4
#> 6 2 3 4

Maybe I could in general (for all recode and transformation functions) make suffix = "" overwrite existing variables.