title: '$' not indexing the column when using function in R
body: <p>I wrote a function so that I can sum the numbers of columns according to a value in another column, but it would not work. Specifically, I wrote this function to sum values of certain columns of a panel data set according to the year value in the column <code>year</code>.</p>
  
  <pre><code>make_sum&lt;-function(df,year_vector,varname){
    datalist = list()
    datalist[[1]]&lt;-year_vector
    # define the vectors for storage
    vector_1&lt;-c()
    vector_2&lt;-c()
    vector_3&lt;-c()
    for (i in 1:length(year_vector)){
      vector_1[i]&lt;-sum(df$sum[df$year == year_vector[i]])
      vector_2[i]&lt;-sum(df$varname[df$year == year_vector[i]])
    }
    # vector_3 as the proportion
    vector_3&lt;-vector_2/vector_1
    # save vectors in the datalist
    datalist[[2]]&lt;-vector_1
    datalist[[3]]&lt;-vector_2
    datalist[[4]]&lt;-vector_3
    names(datalist)&lt;-c("year","sum","soc_wel_sum","prop")
    return(datalist)
  }
  </code></pre>
  
  <p>However, when I run the function on the year_vector and the data frame, I get 0s for <code>vector_2</code>:</p>
  
  <pre><code>one&lt;-make_sum(panel_1,c(2004:2007),"社会中介服务业")
  &gt; one
  $year
  [1] 2004 2005 2006 2007
  
  $sum
  [1] 124477 135157 149316 160921
  
  $soc_wel_sum
  [1] 0 0 0 0
  
  $prop
  [1] 0 0 0 0
  </code></pre>
  
  <p>So, I'm not sure why this is happening, because the <code>varname</code> is indicated correctly:</p>
  
  <pre><code>&gt; panel_1$"社会中介服务业"
    [1]   2   8 105  35  44 106 130   2  25 167  16  56   7
   [14]  39 495  79  74 112  18  15   4   3  84  12  20   0
   [27]  25  58  11  17   8  NA  14  69   8  32  35  39  23
   [40]  18 148  44  39  26  47 240 109  87  43  18   3   4
   [53]   3  93  10  13  NA  24  30  19  25  11   2  22  79
   [66]  21  36  36  34  26  25 170  55  43  14  31 424  97
   [79] 185  47  55   4   7  13  75  16  15  NA  53  32   9
   [92]  30   8   2  13  69  38  40  25  44  23  39 252  41
  [105]  36  10  25 522 139 294  37  39   6   5  24  71  17
  [118]  15  NA  37  38  43  45   7
  </code></pre>