title: Applying a function and assigning multiple variables in a single call in R
body: <p>Some sample R code to consider:</p>
  
  <pre><code>df = data.frame(x=letters[1:4], y=letters[5:8])
  
  find.key &lt;- function(x, li, default=NA) {
    ret &lt;- rep.int(default, length(x))
    for (key in names(li)) {
      ret[x %in% li[[key]]] &lt;- key
    }
    return(ret)
  }
  
  x2 = list("Alpha" = "a", 
            "Beta"  = "b", 
            "Other" = c("c","d"))
  
  y2 = list("Epi"    = "e", 
            "OtherY" = c("f", "g", "h"))
  
  # This is the code in question, imagine many variables and calls to find.key()
  df$NewX2 = find.key(df$x, x2)
  df$Newy2 = find.key(df$y, y2)
  
  # df
  #   x y NewX2  Newy2
  # 1 a e Alpha    Epi
  # 2 b f  Beta OtherY
  # 3 c g Other OtherY
  # 4 d h Other OtherY
  </code></pre>
  
  <p>So the gist of this is I would like to add new variables (NewX2, Newy2) based on a lookup tables (associative arrays/list) via the <a href="https://stackoverflow.com/questions/10431403/idiom-for-ifelse-style-recoding-for-multiple-categories">find.key function</a>.</p>
  
  <p>Is there some way to keep my code DRY? specifically here:</p>
  
  <pre><code>df$NewX2 = find.key(df$x, x2)
  df$Newy2 = find.key(df$y, y2)
  </code></pre>
  
  <p>I'm not sure <code>sapply</code> or <code>lapply</code> could help?  Or perhaps something like <code>%=%</code> as seen <a href="https://stackoverflow.com/questions/7519790/assign-multiple-new-variables-in-a-single-line-in-r">here</a>.</p>
  
  <p>I'd like to something like this...(hopefully this makes sense):</p>
  
  <pre><code>c(df$NewX2, df$Newy2) = find.key(c(df$x, df$y), c(x2, y2))
  </code></pre>