What is the problem with: the condition has length > 1 and only the first element will be used? newbie to r. i have:

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


if i use one &amp; instead of &amp;&amp;, 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 &lt;- function(Age) {
    answer&lt;-NULL
    if(Age&lt;15) answer&lt;-"under 15"
    else if(Age&lt;=50) answer&lt;-"15 to 50"
    else answer&lt;-"over 50"
    answer
}


and got even more warnings:

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


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

age2 &lt;- function(Age) {
    ifelse(Age&lt;15,"under 15",ifelse(Age&lt;=50,"15 to 50","over 50"))
}
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 &lt;- function(Age){
    sapply(Age, function(x) if(x &lt; 15) "under 15" else if (x &lt;= 50) "15 to 50" else "over 50")
}