make.power <- function(n) {
pow <- function(x) {
x^n
}
pow
}
y <- 10
f <- function(x) {
y <- 2
y^2 + g(x)
}
g <- function(x) {
x * y
}
f(3)
## [1] 34
get("y", environment(g))
## [1] 10
get("y", environment(f))
## [1] 10
ls(environment(f))
## [1] "f" "g" "make.power" "y"
# Here, g and f are in the global env. However, y is lexically scoped in
# f.
ls()
## [1] "f" "g" "make.power" "y"
x <- list(a = 1:5, b = rnorm(10))
lapply(x, mean)
## $a
## [1] 3
##
## $b
## [1] 0.146
n <- 1:4
lapply(n, rnorm)
## [[1]]
## [1] 1.486
##
## [[2]]
## [1] -0.6582 -1.0504
##
## [[3]]
## [1] -0.9221 -0.3621 -0.5486
##
## [[4]]
## [1] -0.5309 -0.1827 -0.5513 2.9028
# same as lapply
sapply(n, function(x) {
rnorm(x)
})
## [[1]]
## [1] 0.1756
##
## [[2]]
## [1] 0.1883 -1.0643
##
## [[3]]
## [1] 0.3771 1.2437 -1.4563
##
## [[4]]
## [1] -0.8352 -0.6928 1.2819 0.7325
# but single elem list produces vector
sapply(n, function(x) {
rnorm(1, x)
})
## [1] 1.020 1.233 4.120 3.324
# and constant count elem list > 1 produces matrix:
sapply(n, function(x) {
rnorm(2, x)
})
## [,1] [,2] [,3] [,4]
## [1,] 3.074 0.5032 3.878 4.541
## [2,] 2.101 3.2964 3.977 3.755