title: Extract a column from the dataframe using $ vs bracket [ ] in R
body: <p>I have a function which I need to extract a column, when I use dataframe$column1[i], the function returns an error, but when I use dataframe[, column1][i], it will work. Why can't I just use dataframe$column vs dataframe[, column]???</p>
  <pre><code>function1 &lt;- function(data, x, y) {
  
          data &lt;- arrange(data, x)
  
          ylist &lt;- NULL
  
          for(i in 1:nrow(data)){
                  x0 &lt;- data[, x][i] 
                  data$d0 &lt;- abs(data[,x] - x0)
                  yi &lt;- data %&gt;% arrange(d0) %&gt;% select(y) %&gt;% unlist() %&gt;% mean()
                  ylist &lt;- c(ylist, yi)
  
          }
          return(ylist)
  }
  </code></pre>
  <p>If I wrote the function this way below, it'll return an error: Error in <code>$&lt;-.data.frame</code>(<code>*tmp*</code>, &quot;d0&quot;, value = numeric(0)) : replacement has 0 rows, data has 500</p>
  <pre><code>function1 &lt;- function(data, x, y) {
      
              data &lt;- arrange(data, x)
      
              ylist &lt;- NULL
      
              for(i in 1:nrow(data)){
                      x0 &lt;- data$x[i] 
                      data$d0 &lt;- abs(data$x - x0)
                      yi &lt;- data %&gt;% arrange(d0) %&gt;% select(y) %&gt;% unlist() %&gt;% mean()
                      ylist &lt;- c(ylist, yi)
      
              }
              return(ylist)
      }
  </code></pre>