[R] scalar assignment within a vector within function
peter.langfelder at gmail.com
Fri Mar 30 01:40:49 CEST 2012
On Thu, Mar 29, 2012 at 3:49 PM, Benjamin Caldwell
<btcaldwell at berkeley.edu> wrote:
> I'm trying to create a vector of r^2 values for using a function which I
> will run in a "for" loop. Example:
> temp.i<-fr[fr$per <=(i*.10),]
> with(temp.i, plot(x, y, main=(i*.10),))
> r2<-summary(with(temp.i, lm(y~x)))$adj.r.squared
> legend("bottomright", legend=signif(r2), col="black")
> Test comes up as the original vector of zeros. I know r2 is created for a
> couple reasons (print works, and they show up on the graphs). Also, if I
> run the function line by line with i assigned a number, test[i] is assigned
> as it should be. However, if I call the function, plotter(i), test is not
> modified, although the r^2 prints.
> Mystified. What am I missing?
Add the line
to the end of your function; this will cause the function to return
the value of the vector test.
Then call the function as
test = plotter(1)
You're missing the fact that in R all function arguments are passed by
value (think of them as being copied) and your function assigns a
value in a local copy of the vector test. This copy is discarded when
the function exits. The global copy is not modified. Of course, when
you step through the lines individually (not within a function call),
you work with the global test.
More information about the R-help