Use apply() to a subset of dataframe in R
<p>I am a newbie in this world of R. From whatever I have read, I know that <code>apply()</code> is used to iterate over each row/column in a matrix/vector/dataframe.</p>

<p>I have statement in my code:</p>

<pre><code>a$count &lt;- apply(a[1:9,],1,countRows,species="setosa")
</code></pre>

<p>The <code>coutRows</code> function is as follows:</p>

<pre><code>countRows &lt;- function(x,species){
    count &lt;- sum(iris$sl == x['sl'] &amp; iris$sw == x['sw'] &amp; iris$Species == species)
}
</code></pre>

<p>My intention is to operate over only the first 9 rows in <code>a</code> and add some values to the <code>count</code> column using whatever computation that is done in <code>countRows()</code>. This is why I make use of <code>a[1:9,]</code> as the first argument of  <code>apply()</code>.</p>

<p>For some reason, <code>apply()</code> operates on the complete dataframe. The content of <code>a</code> at the end of execution of above statement is shown below:</p>

<pre><code>     sl   sw count    species
1   low  low     1     setosa
2   mid  low     0     setosa
3  high  low     0     setosa
4   low  mid    32     setosa
5   mid  mid     1     setosa
6  high  mid     0     setosa
7   low high    12     setosa
8   mid high     4     setosa
9  high high     0     setosa
10  low  low     1 versicolor
11  mid  low     0 versicolor
12 high  low     0 versicolor
13  low  mid    32 versicolor
14  mid  mid     1 versicolor
15 high  mid     0 versicolor
16  low high    12 versicolor
17  mid high     4 versicolor
18 high high     0 versicolor
19  low  low     1  virginica
20  mid  low     0  virginica
21 high  low     0  virginica
22  low  mid    32  virginica
23  mid  mid     1  virginica
24 high  mid     0  virginica
25  low high    12  virginica
26  mid high     4  virginica
27 high high     0  virginica
</code></pre>

<p>I expect the remaining 18 rows to contain 0 under <code>count</code> column because I have set everything to 0 initially.</p>

<p>Am I doing anything wrong in the <code>apply()</code> statement?</p>