title: R get object from global environment from function if object exists in global but use different default if not
body: <p>Surely this is possible, but I can't seem to find how to do it:</p>
  
  <p>I'd like to have a default of a function input, but override the default and get() a variable from the global environment if it exists in the global environment. If it doesn't exist in the global environment, take the default of the function, with <strong>any setting in the function being top level and overriding them all.</strong></p>
  
  <p>Ideally it would work like this made-up non-working function:</p>
  
  <pre><code>###Does not work, desired example
  
  myfunc &lt;- function(x=30){
  if(exists.in.global.env(x)){x &lt;- get(x)}
  ###Top level is tough
  if(x.is.defined.as.function.input=TRUE ????){x &lt;- x.defined.as.input}
  }else{ x &lt;- 30} 
  return(x)
  }
  </code></pre>
  
  <p>So that if I do:</p>
  
  <pre><code>myfunc()
  [1] 30
  </code></pre>
  
  <p>But if I create x I want it to override the default x=30 of the function and take the global environment value instead:</p>
  
  <pre><code>x &lt;- 100
  myfunc()
  [1] 100
  </code></pre>
  
  <p>But if I have x defined inside the function, I'd like that to be top level, i.e. override everything else even if x is defined globally:</p>
  
  <pre><code>x &lt;- 100
  myfunc(x=300)
  [1] 300
  </code></pre>
  
  <p>Thanks in advance!</p>