Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdate Variable within Loop in R
    primarykey
    data
    text
    <p>How should I modify my code to update variables within a loop?</p> <p>Specifically, I want to do something like the following:</p> <pre><code>myMatrix1 &lt;- read.table(someFile) myMatrix2 &lt;- read.table(someFile2) for (i in nrow(myMatrix2)) { myMatrix3 &lt;- myMatrix1[which(doSomeTest),] myMatrix4 &lt;- rep(myMatrix2$header1,nrow(myMatrix1)) myMatrix5 &lt;- rep(myMatrix2$header2, nrow(myMatrix1)) myMatrix6 &lt;- cbind(myMatrix3, myMatrix4, myMatrix5) # *see question } </code></pre> <p>How can I get myMatrix6 to be updated instead of reassigned the product of <code>cbind(myMatrix3, myMatrix4, myMatrix5)</code>? In other words, if the first iteration (i = 1) gave a myMatrix6 of:</p> <pre><code>&gt; 1 1 1 1 &gt; 2 2 2 2 </code></pre> <p>and the second iteration (i = 2) gave myMatrix 6 of:</p> <pre><code>&gt; 3 3 3 3 &gt; 4 4 4 4 </code></pre> <p>how do I get a dataframe(?) of:</p> <pre><code>&gt; 1 1 1 1 &gt; 2 2 2 2 &gt; 3 3 3 3 &gt; 4 4 4 4 </code></pre> <p>UPDATE:</p> <p>I have - thanks to DWin and Timo's suggestions - got the following. However, the following code has taken me about 2 hours to run on my datasets. Are there any ways to make it run any faster??? (without using a more powerful computer I may add)</p> <pre><code># create empty matrix for sedimentation myMatrix6 &lt;- data.frame(NA,NA,NA,NA)[0,] names(myMatrix6) &lt;- letters[1:4] # create empty matrix for bore myMatrix7 &lt;- data.frame(NA,NA,NA,NA)[0,] names(myMatrix7) &lt;- letters[1:4] for (i in 1:nrow(myMatrix2)) { # create matrix that has the value of myMatrix1$begin being # situated between the values of myMatrix2begin[i] and myMatrix2finish[i] myMatrix3 &lt;- myMatrix1[which((myMatrix1$begin &gt; myMatrix2$begin[i]) &amp; (myMatrix1$begin &lt; myMatrix2$finish[i])),] myMatrix4 &lt;- rep(myMatrix2$sedimentation, nrow(myMatrix3)) if (is.na(myMatrix2$boreWidth[i])) { myMatrix5 &lt;- rep(NA, nrow(myMatrix3)) } else if (myMatrix2$boreWidth[i] == 0) { myMatrix5 &lt;- rep(TRUE, nrow(myMatrix3)) } else if (myMatrix2$boreWidth[i] &gt; 0) { myMatrix5 &lt;- rep(FALSE, nrow(myMatrix3)) } myMatrix6 &lt;- rbind(myMatrix6, cbind(myMatrix3, myMatrix4)) myMatrix7 &lt;- rbind(myMatrix7, cbind(myMatrix3, myMatrix5)) } </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.
    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