title: apply() in R with user-defined function
body: <p>I have a data frame with votes and party labels arranged thus</p>
  
  <pre><code>dat &lt;- data.frame( v1=c(25, 0, 70), 
                     v2=c(75, 100, 20), 
                     v3=c(0, 0, 10), 
                     l1=c("pA", ".", "pB"), 
                     l2=c("pB", "pC", "pC"), 
                     l3=c(".", ".", "pD") )
  </code></pre>
  
  <p>so that each row is a unit of analysis. Only vote-getting parties need consideration and this function extracts positive votes or the corresponding labels</p>
  
  <pre><code>getpos &lt;- function(vector, vorl="v"){ # change to "l" to report labels
      vot &lt;- vector[grep( "v", colnames(vector) )]; 
      lab &lt;- vector[grep( "l", colnames(vector) )];
      if (vorl=="v") {vot[vot&gt;0]} else {lab[vot&gt;0]};
  }
  getpos(dat[1,])           # votes for obs 1
  getpos(dat[1,], vorl="l") # labels for obs 1
  </code></pre>
  
  <p>I wish to run function getpos in every row of data frame dat in order to produce lists with vote/label vectors of different length. Applying the function does not return what I expect:</p>
  
  <pre><code>apply(X=dat, MARGIN=1, FUN=getpos, vorl="l")
  </code></pre>
  
  <p>Can anyone spot the problem? And related, can this be achieved more efficiently?</p>