Search code examples
rif-statementrecode

Using if, else within recode


I am trying to replicate some code, but am running into trouble:

data$var1 has values from 1-7 which I am trying to reduce to just 2 value in a new variable called data$var2. The code looks like this:

data$var2 <- recode(data$var1, "1:3=1; else=0")

However, when I execute code, I get the following error:

"Error: Argument 2 must be named, not unnamed"

I'm working in the latest version of R and using the Tidyverse package.

What am I missing? What does 'Argument 2 unnamed' mean?


Solution

  • I would advise using ifelse:

    data$var2 <- ifelse(data$var1 < 4, 1, 0)
    

    Your use of recode is wrong:

    data$var2<- recode(data$var1, "1:3=1; else=0")
    

    Instead of several arguments [name]=[replacement] you provided only one string. For more information read help('recode').

    "Correct" way with recode would be something like

    data$var2 <- recode(data$var1, `1` = 1, `2` = 1, `3` = 1, .default = 0)
    

    But you should stick with ifelse in this case.