title: R subsetting data frame by column
body: <p>For an assignment, I have written a function with "id" as an argument, in which I create a null data frame, then in a for loop read the number of complete cases (no NAs) in a series of CSV files. This gives me a data frame "dat" with two columns (id, # complete cases), which I have verified. Now I'm having trouble subsetting this based on the id argument. I should be able to subset by column 1 which is equivalent to the id:</p>
  
  <pre><code>dat[which(dat[, 1] %in% id),]
  </code></pre>
  
  <p>but when I run this function, nothing is returned (no output, no error). After some searching on this site and others, I tried naming the columns when I created the data frame, to have something to call the column in subsetting:</p>
  
  <pre><code>dat &lt;- data.frame("monitor"=integer(), "nobs"=integer())
  dat_subset &lt;- dat[which(dat[, "monitor"] %in% id),]
  </code></pre>
  
  <p>but this returns "undefined columns selected". So I tried specifying my data frame another way:</p>
  
  <pre><code>dat &lt;- data.frame(ncol=2)
  colnames(dat) &lt;- c("ID", "nobs")
  </code></pre>
  
  <p>but this gives error 'names' attribute [2] must be same length as vector [1]. What is the length 1 vector? Didn't I ask for a 2 column data frame?</p>
  
  <p>Can anyone help me to debug any of these options? Many thanks!</p>
  
  <p>Edit based on feedback: I initialized by data frame properly (thanks to the comments). 
      dat &lt;- data.frame("ID" = integer(0), "nobs" = integer(0))
  <code>Str(dat)</code> shows I have done this correctly
      'data.frame':   0 obs. of  2 variables:
       $ ID  : int 
       $ nobs: int 
  So it seems that my problem lies in the for loop that follows, as using <code>str(dat)</code> after the loop shows the column names have been dropped:</p>
  
  <pre><code>for (i in 1:332) {
          nobs &lt;- sum(complete.cases(read.csv(files_list[i])))
          rowvector &lt;- c(i,nobs)
          dat &lt;- rbind(dat, rowvector)
    }
  'data.frame':   332 obs. of  2 variables:
   $ X1L  : int  1 2 3 4 5 6 7 8 9 10 ...
   $ X117L: int  117 1041 243 474 402 228 442 192 275 148 ...
  </code></pre>
  
  <p>Why would the names not stick when adding lines to the data frame? <code>?rbind</code> states that "column names are taken from the first argument with appropriate names".</p>