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?