title: How to use "within" in R?
body: <p>I've been struggling with finding a way to evaluate an R expression in an environment constructed from data. I have a dataframe:</p>
  
  <pre><code>    head(DATA1) 
      COD_CLI      ENDEUD_FINAL
      1 01002901 Mediana Empresa
      2 01002932 No Sobreendeudado
      3 04203409 No Sobreendeudado
      ...
  </code></pre>
  
  <p>and I try to complete another data (DATA2):</p>
  
  <pre><code>    head(DATA2) 
      COD_CLI_W      ENDEUD_FINAL
      1 01002190   
      2 01002913   
      3 04203401   
      ...
  </code></pre>
  
  <p>DATA2 is larger than DATA1, if the same COD_CLI/COD_CLI_W is in both datas, I take the second column of DATA1, if not I must evaluate another dataframe "wallet":</p>
  
  <pre><code>    &gt; str(wallet)
      'data.frame':   81101 obs. of  8 variables:
      $ COD_CREDITO     : chr  "0040410166104" "00000363393"          "0060030164135" "004023854M" ...
      $ COD_CLI         : chr  "00402037" "00166750" "00178607" "40097700" ...
      $ TIPO_DE_CREDITO : chr  "12.-CONSUMO NO REVOLVENTE" "10.-MICROEMPRESA" "10.-MICROEMPRESA" "10.-MICROEMPRESA" ...
      $ SITUACION_SAFI  : chr  "CASTIGADO" "CASTIGADO" "CASTIGADO" "CASTIGADO" ...
      $ COD_TIP_PRESTAMO: chr  "0747" "0748" "0748" "0747" ...
      $ ATR_SOL         : num  0 0 0 0 0 0 0 0 0 0 ...
      $ CAP_SOL         : num  313.37 3.16 1670.51 3010 2327.71 ...
      $ NUM_ENT         : num  3 1 2 1 1 3 2 1 4 2 ...
  </code></pre>
  
  <p>Now the code I run is:</p>
  
  <pre><code>    DATA2 &lt;- within(DATA2,{
      CALIF_RCD &lt;- ifelse(COD_CLI_W %in% DATA1$COD_CLI,DATA1$ENDEUD_FINAL[which(DATA1$COD_CLI %in% COD_CLI_W)],
      ifelse(wallet$TIPO_DE_CREDITO[which(wallet$COD_CLI %in% COD_CLI_W)[1]] == "08.-MEDIANA EMPRESA","Mediana Empresa",
      ifelse(wallet$NUM_ENT[which(wallet$COD_CLI %in% COD_CLI_W)[1]]&lt;5,"No Sobreendeudado","Sobreendeudado")))
      }
      )
  </code></pre>
  
  <p>the output is wrong in most of the cases. I'm new to R and I would like to know how to code it in a properly manner. Any help would be much appreciated.</p>