I could never figure out how scoping works in R, so I pasted it here. Bottom line: things like if blocks do not have their own scope.
> x <- 1
> y <- 2
> z <- 3
>
> my.func <- function() {
+ print(sprintf("%d %d %d %d", x, y, z, w))
+ y <- 102
+ if (TRUE) {
+ z <- 103
+ w <- 104
+ print(sprintf("%d %d %d %d", x, y, z, w))
+ }
+ print(sprintf("%d %d %d %d", x, y, z, w))
+ }
>
>
> if (TRUE) {
+ w <- 4
+ }
> print(sprintf("%d %d %d %d", x, y, z, w))
[1] "1 2 3 4"
>
> print("Calling my.func")
[1] "Calling my.func"
> my.func()
[1] "1 2 3 4"
[1] "1 102 103 104"
[1] "1 102 103 104"
> print("Done with my.func")
[1] "Done with my.func"
>
> print(sprintf("%d %d %d %d", x, y, z, w))
[1] "1 2 3 4"
Tuesday, November 17, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment