title: Why doesn't this R function either work or throw an error? (Scoping issue?)
body: <p>This builds a simple data frame, and applies a function to both of its rows.
  However, </p>
  
  <pre><code>name2num[[name]] = uid 
  </code></pre>
  
  <p>fills in <code>name2num</code>, while </p>
  
  <pre><code>num2name[uid] = name 
  </code></pre>
  
  <p>doesn't fill in <code>num2name</code>.</p>
  
  <pre><code>numbers = c(1,2)
  names = c('a', 'b')
  df = data.frame(numbers, names)
  name2num = new.env()
  num2name = integer(nrow(df))
  f = function(row) {
      uid = as.integer(row[1])
      name = row[2]
      name2num[[name]] = uid
      num2name[uid] = name
  }
  </code></pre>
  
  <p>These are my tests:</p>
  
  <blockquote>
    <p>apply(df, 1, f)<br>
    [1] "a" "b"<br>
    name2num[['a']]<br>
    [1] 1<br>
    name2num[['b']]<br>
    [1] 2<br>
    num2name<br>
    [1] 0 0  </p>
  </blockquote>
  
  <p>I could understand this if <code>num2name</code> inside the function were a local variable, but if it were, I should get an 'object not found' error message.</p>
  
  <p>I know that it would be better to write the function to pass the results back, but I want to know what R is doing and why it neither throws an error, nor writes to num2name. Why doesn't it either write to the global variable, or throw an object not found error, like it would if I used the name of a variable not defined in the calling environment?</p>
  
  <pre><code>f = function(row) {
      uid = as.integer(row[1])
      name = row[2]
      name2num[[name]] = uid
      foo[uid] = name
  }
  </code></pre>
  
  <blockquote>
    <p>apply(df, 1, f)<br>
        Error in foo[uid] = name : object 'foo' not found</p>
  </blockquote>