0

I've searched through some of the previous posts on this subject and haven't found something to answer my question.

I'm doing the following:

brfss2013[, "hExcellent"] <- ifelse(brfss2013$genhlth == 'Excellent') 1, 0

Error: unexpected numeric constant in "brfss2013[, "hExcellent"] <- ifelse(brfss2013$genhlth == 'Excellent') 1"

Not sure what the problem is. I'm simply trying to place a 1 or 0 in my new column based on what my evaluation of the condition is.

Any help is appreciated. Thanks.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
Bill
  • 13
  • 2

1 Answers1

1

Two issues:

  1. Your ifelse syntax is incorrect. If should be ifelse(condition, TRUE, FALSE) (note the brackets). See also ?ifelse.

  2. More importantly, since you return 1 or 0 (depending on the condition), you don't need ifelse at all.

    brfss2013[, "hExcellent"] <- +(brfss2013$genhlth == 'Excellent')
    

    suffices and is faster. The unary operator + is explained in ?`+`.

    Alternatively you can also use as.integer

    brfss2013[, "hExcellent"] <- as.integer(brfss2013$genhlth == 'Excellent')
    

Lastly and for future posts, it's always better to include some form of minimal representative sample data to make your issue/problem/error reproducible. Ideally, potential SO respondents should be able to copy&paste your sample data and code into a terminal, and reproduce the issue that you describe. To improve your post, take a look at what to consider when providing a minimal reproducible example/attempt.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • 1
    This makes sense. Thank you very much Maurits. Definitely had misplaced brackets and commas. I didn't included a code snipet as I thought the question was simple enough that people looking at it could answer but I'll do that next time. Thanks again. – Bill Aug 23 '18 at 23:18
  • You're very welcome @Bill and welcome to SO! – Maurits Evers Aug 23 '18 at 23:25