What is the problem with: the condition has length > 1 and only the first element will be used?

newbie to r. i have:

  age - function(Age) {
 +     answer-NULL
 +     if(Age15) answer-"under 15"
 +     else if(15=AgeAge=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(Age15) 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(Age15,"under 15",ifelse(Age=50,"15 to 50","over 50"))
}

Topic homework r

Category Data Science


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")
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.