Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You might want to change your <code>getNumberInfo</code> function to return a list rather than a vector, so that the values can have different types. As it is, they're all being cast to strings, which probably isn't what you want for <code>logX</code>.</p> <pre><code>getNumberInfo &lt;- function(x) { if(x %% 2 ==0) evenness = "Even" else evenness="Odd" if(x &gt; 0) positivity = "Positive" else positivity = "NonPositive" if (positivity == "Positive") logX = log(x) else logX=NA list(evenness,positivity,logX) } </code></pre> <p>Furthermore, you can use the names to a somewhat better effect so that you don't have to repeat them:</p> <pre><code>getNumberInfo &lt;- function(x) { list(evenness = if(x %% 2 ==0) "Even" else "Odd", positivity = if(x &gt; 0) "Positive" else "NonPositive", logX = if(x &gt; 0) log(x) else NA) } </code></pre> <p>Then the solution becomes simple:</p> <pre><code>&gt; cbind(myDF, t(sapply(myDF$Value, getNumberInfo))) Value evenness positivity logX 1 -2 Even NonPositive NA 2 -1 Odd NonPositive NA 3 0 Even NonPositive NA 4 1 Odd Positive 0 5 2 Even Positive 0.6931472 </code></pre> <p>Finally, if you use <code>ifelse</code> (which can work on vectors) instead of <code>if</code>, it gets even simpler because you don't have to call <code>apply</code>:</p> <pre><code>getNumberInfo &lt;- function(x) { list(evenness = ifelse(x %% 2 ==0, "Even", "Odd"), positivity = ifelse(x &gt; 0, "Positive", "NonPositive"), logX = ifelse(x &gt; 0, log(x), NA)) } &gt; cbind(myDF, getNumberInfo(myDF$Value)) Value evenness positivity logX 1 -2 Even NonPositive NA 2 -1 Odd NonPositive NA 3 0 Even NonPositive NA 4 1 Odd Positive 0.0000000 5 2 Even Positive 0.6931472 </code></pre> <p>That last solution emits a warning, because it's actually computing the log of every element, not just those with <code>x&gt;0</code>. Not sure the most elegant way to deal with that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload