1

I want to create another binary variable y condition on different categories of the variable x.

if the variable x is "a" or "b" or "c" I want y to be equal to 1, if x is "d" or "e" y=0

My code is as follows

data$y <- ifelse(data$x == "a" | data$x == "b" |data$x == "c", 1, 
ifelse(data$x == "d" | data$loan_status == "e" ,0))

I am receiving an error :

argument "no" is missing, with no default"

I have checked other similar questions but that does not solve my problem.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Erick
  • 133
  • 2
  • 3
  • 16
  • 1
    It's asking for value when `data$x == "d" | data$loan_status == "e"` is `FALSE` – CPak Jun 12 '18 at 21:23
  • the question `argument “no” is missing, with no default` already exists, that's why you had to mispell yours, and it contains your answer... – moodymudskipper Jun 12 '18 at 21:32

1 Answers1

6

ifelse requires 3 arguments, the first is called test, the second is called yes, the third is called no.

Your inner ifelse statement only has two arguments, which is not enough:

ifelse(data$x == "d" | data$loan_status == "e", 0)

Hence the third argument, no, is missing. I would recommend setting it to something like NA, that way anything that does not meet either of your conditions will be set to the missing value NA.

As a side note, the %in% function is a lot nicer to use than lots of ORs. I would rewrite your code one of two ways:

# this is nice and simple if you are sure data$x only takes values
# a,b,c,d,e
ifelse(data$x %in% c("a", "b", "c"), 1, 0)

# this is good if there is even a tiny chance data$x has other values
# it will flag the other values as NA
ifelse(data$x %in% c("a", "b", "c"), 1, ifelse(data$x %in% c("c", "d"), 0, NA))
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294