3
$\begingroup$

newbie to r. i have:

> > age <- function(Age) {
> +     answer<-NULL
> +     if(Age<15) answer<-"under 15"
> +     else if(15<=Age&&Age<=50) answer<-"15 to 50"
> +     else answer<-"over 50"
> +     answer
> + }
> > titanic_3 <- titanic %>% 
> +     select(Survived, Pclass, Age, Sex) %>%
> +     filter(!is.na(Age)) %>%
> +     mutate(agecat=age(Age)) Warning message: In if (Age < 15) answer <- "under 15" else if (15 <= Age && Age <=  :   the condition has
> length > 1 and only the first element will be used
> >

if i use one & instead of &&, i get two warnings. i know that one of these is because of the shortcut thing.

how do i write this function so as to get rid of the warning message?

thanks

edit: i tried:

age <- function(Age) {
    answer<-NULL
    if(Age<15) answer<-"under 15"
    else if(Age<=50) answer<-"15 to 50"
    else answer<-"over 50"
    answer
}

and got even more warnings:

Warning messages:
1: In if (Age < 15) answer <- "under 15" else if (Age <= 50) answer <- "15 to 50" else answer <- "over 50" :
  the condition has length > 1 and only the first element will be used
2: In if (Age <= 50) answer <- "15 to 50" else answer <- "over 50" :
  the condition has length > 1 and only the first element will be used

this one seems to work, but they want us to use cut.

age2 <- function(Age) {
    ifelse(Age<15,"under 15",ifelse(Age<=50,"15 to 50","over 50"))
}
$\endgroup$

1 Answer 1

4
$\begingroup$

The reason you receive a warning is that Age is a vector, but you are comparing it with a scalar. R automatically takes the first element of Age. You can use "ifelse" and convert the class if needed.

If you want to limit yourself to base R, you can use the following:

age <- function(Age){
    sapply(Age, function(x) if(x < 15) "under 15" else if (x <= 50) "15 to 50" else "over 50")
}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.