简体   繁体   中英

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?

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.

There are many to do this, probably many of them are easier than my approach.

 # Create some data
 df      <- c()
 df$var1 <- ceiling(runif(20, min = 0.5, max = 7.5))
 df$var1
 #  [1] 5 8 5 2 6 6 8 4 5 4 4 7 3 6 1 5 7 6 5 6

 # inds will contain TRUE/FALSE 
 inds           <- (df$var1 <= 3)
 df$var2[inds]  <- 1
 df$var2[!inds] <- 0
 df$var2
 # [1] 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1

Sidenote: I used df as my object's name, because it is not a good idea to call objects data . The name data is reserved in R for other purposes (see ?data ). Even though in this case it will probably not lead to problems, I still recommend using df (or anything else) instead of data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM