1

I tried to discretise a column in dataframe df using ifelse statements using the following code. The column aar contains decimal values from 0 to 12 and NAs. I check if the numeric value and assign it to the categories as below.

> df= df%>% mutate(arr2= ifelse( grepl("NA", aar)==T, "NA",
> ifelse(as.numeric(aar)==0, "0-0.99", ifelse(as.numeric(aar))==1,
> "1-1.99", ifelse(as.numeric(aar)==2, "2-2.99",
> ifelse(as.numeric(aar)==3, "3-3.99", ifelse(as.numeric(aar)==4,
> "4-4.99", ifelse(as.numeric(aar)==5, "5-5.99",
> ifelse(as.numeric(aar)==6, "6-6.99", ifelse(as.numeric(aar)==7,
> "7-7.99", ifelse(as.numeric(aar)==8,
> "8-8.99",ifelse(as.numeric(aar)==9, "9-9.99",
> ifelse(as.numeric(aar)==10, "10-10.99",  ifelse(as.numeric(aar)==11,
> "11-11.99", "12" )))))))))))))

But I get the following error,

Error: unused arguments ("1-1.99", ifelse(as.numeric(c("0", "NA", "0",...... 

What am I doing wrong? Can anyone kindly help me to fix this please?

andy
  • 643
  • 2
  • 12
  • 20
  • 1
    Use `cut()` or `factor()` instead. – zx8754 Jun 23 '16 at 07:23
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Jun 23 '16 at 07:23

1 Answers1

4

You are prematurely closing a parenthesis in your second call to ifelse:

> ifelse(as.numeric(aar)==0, "0-0.99", ifelse(as.numeric(aar))==1,

should be:

> ifelse(as.numeric(aar)==0, "0-0.99", ifelse(as.numeric(aar)==1,

I'm not an R guru like @akrun, but there must be a better way to achieve what you are trying to do, instead of nesting 12 ifelse calls. Your current approach makes the code hard to read, and harder to debug (hence your question).

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360