我定义了一个函数:
.get <- function( o, ...) {
p <- match.call( expand.dots = 0)$...
cat( sprintf( 'In .get, it is %s.\n', eval( tail( p, 1)[[ 1]])))
fn <- switch( typeof( o), list =, environment = `[[`, 'S4' = '@', `[`)
if( length( p)) eval( as.call( c( fn, quote( o), p))) else o # Here when true, I compose a call based on p.
}
然后我尝试了如下:
it <- 1
m <- matrix( seq( 9), 3)
sapply( seq( 3), function( it) {
cat( sprintf( 'In sapply, it is: %s.\n', it))
.get( m, , it)
})
sapply( seq( 3), function( it) .get( m, , it))
输出:
In sapply, it is: 1.
In .get, it is 1.
In sapply, it is: 2.
In .get, it is 1.
In sapply, it is: 3.
In .get, it is 1.
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 3 3
但预期输出是:
In sapply, it is: 1.
In .get, it is 1.
In sapply, it is: 2.
In .get, it is 2.
In sapply, it is: 3.
In .get, it is 3.
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
那么为什么是it
不是 1 到 3(调用函数时的值),而是始终在全局环境中分配的值(即 1)?