[R] Beginners problem
Rolf Wester
rolf.wester at ilt.fraunhofer.de
Mon Oct 4 16:01:15 CEST 2004
Hi,
I'm new to R and have a problem with a little test program (see below).
Why doesn't <<- in function rk4
assign the new value to y so that it is seen in rktest. I thought that
<<- does exactly this. But it seems that I
didn't get it right. I would be very appreciative for an explanation of
that behaviour of <<-. I know how to
write the whole thing so that it works (return the updated y to rktest)
but I would like to learn how variable scope
in R works.
Thanks in advance
Rolf
----------------------------------------------------------------------------------------------------------------------
rk4 <- function(x,y,f,h) {
n <- length(y)
hh <- h*0.5
k1 <- f(x,y)
k2 <- f(x,y+k1*hh)
k3 <- f(x,y+k2*hh)
k4 <- f(x,y+k3*h)
y <<- y + h/6.0*(k1 + 2.0*k2 + 2.0*k3 + k4))
}
rkf <- function(x,y) {
-y
}
rktest <- function(){
y <- 1.0
x <- 0.0
h <- 0.1
for(i in 1:10) {
rk4(x,y,rkf,h)
print(y)
}
}
rktest()
More information about the R-help
mailing list