I’m writing my first function ever (including any other programming language) and I’m a little confused on the proper structure for if, else and ifelse. I’ve searched a ton of examples, but none are that clear to me.
Situation – I’m trying to bucket clients by how long they have been clients for, then turn that into a factor.
#Sample Data
clientID <- round(runif(2,min=2000, max=3000),0)
MonthsSinceSignUp <- round(runif(20,min=1, max=60),0)
df <- data.frame(cbind(clientID,MonthsSinceSignUp))
For a given client, I would like to determine if they have been so for less than a year, more than year, but less than 2, etc.
This is my first crack at a function:
ClientAgeRange <- function(MonthsSinceSignUp) {
if (MonthsSinceSignUp < 13) {ClientAgeRange <- '1 year'}
} else {
if (MonthsSinceSignUp > 13 & MonthsSinceSignUps < 25) {ClientAgeRange <- '2 years'}
} else {ClientAgeRage <- '3+ years'}
The error that I keep getting is:
Error: unexpected '}' in "}", which would indicate I’m missing or have an extra closing bracket. However, despite my trouble shooting, I can’t locate it. But – I think in general, I’m not apply the correct structure to the function. I’m trying to produce a if this, then set this variable as that. How can I structure this function properly?
Lastly – if I wanted to add the output of the function to the dataframe, is apply the correct way to do so?
An answer in two parts:
The tip:
My first tip is to use a code editor that does bracket matching. For example, in
Notepad++you get this:PS. I’m not recommending
Notepad++– use Rstudio instead – I’m simply usingNotepad++because of the garish (and thus easy to spot) coloursNotice that the highlighted brace (in red) matches with a brace in the middle of your function. This reveals that there is redundant brace at the end of your first
if. So, fix that first:OK, now there is no matching brace (no highlighted red), so you need to add the missing brace at the end of your function:
The fix:
But you can vastly simplify your function if you use
cut, which is designed to do this type of analysis:Try it on your code: