title: retrieve environment values with get(ls()) in R
body: <p>I wanted to write a simple function in R that parses through the variables in <code>ls()</code> and takes their value. however, I'm not sure what I'm doing wrong since when I run the following code:</p>
  
  <pre><code>a &lt;- 1
  b &lt;- 2
  l &lt;- c("a", "b")
  get_val &lt;- function(x){
    for(i in 1:length(x)){
      print(paste(x[i]))
      if(x[i] %in% ls()){
        print(paste(x[i], "value is", get(ls()[which(ls() %in% x[i])])))
      }
    }
  }
  
  get_val(l)
  </code></pre>
  
  <p>this returns only</p>
  
  <pre><code>&gt; get_val(l)
  [1] "a"
  [1] "b"
  </code></pre>
  
  <p>while if I run only the for loop inside the function as:</p>
  
  <pre><code>  for(i in 1:length(l)){
      print(paste(l[i]))
      if(l[i] %in% ls()){
        print(paste(l[i], "value is", get(ls()[which(ls() %in% l[i])])))
      }
    }
  </code></pre>
  
  <p>I get correctly</p>
  
  <pre><code>[1] "a"
  [1] "a value is 1"
  [1] "b"
  [1] "b value is 2"
  </code></pre>
  
  <p>I'm not really sure why that is, any input would be awesome, thanks :)</p>