I defined a function:
.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.
}
Then I tried it as follows:
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))
The output:
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
But the expected output is:
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
So why is it
not 1 to 3 (the value it has where the function was called), but always the value assigned in the global environment (i.e. 1)?