title: How to paste factor labels conditionally in R
body: <p>Hope someone can help me on this one for which I have just found a lousy solution on my own: I would like to aggregate (or paste) the labels of four columns (<code>A</code> to <code>D</code>) into a fifth (<code>dream</code>) but conditionally, that is only if its numeric value is 2. </p>
  
  <p>Here is my database <code>df</code>: </p>
  
  <pre><code>id= c(1:12)
  A = c(2,NA,NA,2,NA,1,1,1,1,1,NA,2)
  B = c(2,1,1,1,2,NA,1,1,1,1,2,1)
  C = c(2,1,1,1,2,NA,1,1,1,1,NA,1)
  D = c(2,1,1,1,1,1,2,1,1,NA,2,1)
  df = data.frame(id,A,B,C,D) ; df
  df$A=factor(df$A, labels=c("no", "i saw"))
  df$B=factor(df$B, labels=c("no", "someone"))
  df$C=factor(df$C, labels=c("no", "sitting"))
  df$D=factor(df$D, labels=c("no", "on a cloud")) ; df
  </code></pre>
  
  <p>Here is below the solution i found, but not so satisfying...</p>
  
  <pre><code>df$dream = ifelse(as.numeric(df$A)!=2, NA, as.character(df$A)) ; df
  df$dream = ifelse(as.numeric(df$B)!=2, df$dream, paste(df$dream, as.character(df$B))) ; df
  df$dream = ifelse(as.numeric(df$C)!=2, df$dream, paste(df$dream, as.character(df$C))) ; df
  df$dream = ifelse(as.numeric(df$D)!=2, df$dream, paste(df$dream, as.character(df$D))) ; df
  </code></pre>
  
  <p>I am sure there is a straightfoward way to do so, in addition my code doesn't even seem to work this way.. Could someone help me? Thanks </p>