Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Looks like you have an environment problem. Global assignment fixes the problem, but at the cost of one's soul:</p> <pre><code>library(plyr) a = c(1,2,3,4) b = c(0,0,1,1) c = c(5,6,7,8) d.f = data.frame(a,b,c) sv = c("b") ColName = "a" ddply(d.f, sv, summarize, Ave = mean(eval(parse(text=ColName)), na.rm=TRUE) ) myFunction &lt;- function(x, y){ NewColName &lt;&lt;- "a" z = ddply(x, y, summarize, Ave = mean(eval(parse(text=NewColName)), na.rm=TRUE) ) return(z) } myFunction(x=d.f,y=sv) </code></pre> <p><code>eval</code> is looking in parent.frame(1). So if you instead define NewColName outside MyFunction it should work:</p> <pre><code>rm(NewColName) NewColName &lt;- "a" myFunction &lt;- function(x, y){ z = ddply(x, y, summarize, Ave = mean(eval(parse(text=NewColName)), na.rm=TRUE) ) return(z) } myFunction(x=d.f,y=sv) </code></pre> <p>By using <code>get</code> to pull out my.parse from the earlier environment, we can come much closer, but still have to pass curenv as a global:</p> <pre><code>myFunction &lt;- function(x, y){ NewColName &lt;- "a" my.parse &lt;- parse(text=NewColName) print(my.parse) curenv &lt;&lt;- environment() print(curenv) z = ddply(x, y, summarize, Ave = mean( eval( get("my.parse" , envir=curenv ) ), na.rm=TRUE) ) return(z) } &gt; myFunction(x=d.f,y=sv) expression(a) &lt;environment: 0x0275a9b4&gt; b Ave 1 0 1.5 2 1 3.5 </code></pre> <p>I suspect that <code>ddply</code> is evaluating in the .GlobalEnv already, which is why all of the <code>parent.frame()</code> and <code>sys.frame()</code> strategies I tried failed.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload