Note that there are some explanatory texts on larger screens.

plurals
  1. POR - vectorised conditional replace
    primarykey
    data
    text
    <p>Hi I'm trying manipulate a list of numbers and I would like to do so without a for loop, using fast native operation in R. The pseudocode for the manipulation is :</p> <blockquote> <p>By default the starting total is 100 (for every block within zeros) </p> <p>From the first zero to next zero, the moment the cumulative total falls by more than 2% replace all subsequent numbers with zero.</p> <p>Do this far all blocks of numbers within zeros</p> <p>The cumulative sums resets to 100 every time </p> </blockquote> <p>For example if following were my data :</p> <pre><code>d &lt;- c(0,0,0,1,3,4,5,-1,2,3,-5,8,0,0,-2,-3,3,5,0,0,0,-1,-1,-1,-1); </code></pre> <p>Results would be :</p> <pre><code>0 0 0 1 3 4 5 -1 2 3 -5 0 0 0 -2 -3 0 0 0 0 0 -1 -1 -1 0 </code></pre> <p>Currently I have an implementation with a for loop, but since my vector is really long, the performance is terrible.</p> <p>Thanks in advance.</p> <p>Here is a running sample code :</p> <pre><code>d &lt;- c(0,0,0,1,3,4,5,-1,2,3,-5,8,0,0,-2,-3,3,5,0,0,0,-1,-1,-1,-1); ans &lt;- d; running_total &lt;- 100; count &lt;- 1; max &lt;- 100; toggle &lt;- FALSE; processing &lt;- FALSE; for(i in d){ if( i != 0 ){ processing &lt;- TRUE; if(toggle == TRUE){ ans[count] = 0; } else{ running_total = running_total + i; if( running_total &gt; max ){ max = running_total;} else if ( 0.98*max &gt; running_total){ toggle &lt;- TRUE; } } } if( i == 0 &amp;&amp; processing == TRUE ) { running_total = 100; max = 100; toggle &lt;- FALSE; } count &lt;- count + 1; } cat(ans) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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