Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use acast (reshape2) within a function in R?
    text
    copied!<p>I tried to use <code>acast</code> from <code>reshape2</code> within a self written function, but had the problem that acast did not find the data I send to it.</p> <p>Here is my data:</p> <pre><code>library("reshape2") x &lt;- data.frame(1:3, rnorm(3), rnorm(3), rnorm(3)) colnames(x) &lt;- c("id", "var1", "var2", "var3") y &lt;-melt(x, id = "id", measure = c("var1", "var2", "var3")) </code></pre> <p><code>y</code> then looks like this:</p> <pre><code> id variable value 1 1 var1 0.1560812 2 2 var1 1.0343844 3 3 var1 -1.4157728 4 1 var2 0.8808935 5 2 var2 0.1719239 6 3 var2 0.6723758 7 1 var3 -0.7589631 8 2 var3 1.1325995 9 3 var3 -1.5744876 </code></pre> <p>now I can cast it back via <code>acast</code>:</p> <pre><code>&gt; acast(y,y[,1] ~ y[,2]) var1 var2 var3 1 0.1560812 0.8808935 -0.7589631 2 1.0343844 0.1719239 1.1325995 3 -1.4157728 0.6723758 -1.5744876 </code></pre> <p>However, when writing a small wrapper for <code>acast</code> that should do the same, i get a stupid error messages:</p> <pre><code>wrap.acast &lt;- function(dat, v1 = 1, v2 = 2) { out &lt;- acast(dat, dat[,v1] ~ dat[,v2]) return(out) } wrap.acast(y) Error in eval(expr, envir, enclos) : object 'dat' not found </code></pre> <p>The problem is obviously related to something like environments and global/local variables. As it gives other error messages after declaring <code>dat</code> in the global environment (i.e., <code>v1</code> and <code>v2</code> not found as long as they aren't global).</p> <p><strong>I would like to use resahpe (especially acast) within a function without the necessity of declaring the variables outside the function. What is the trick?</strong></p> <p>Thanks.</p>
 

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