I am confused about how bquote handles multidimensional terms (e.g., a matrix)
wrapped in .().
Suppose I have the following X matrix.
# Set a seed exact draws.
set.seed(2023)
# Create a matrix.
X <- matrix(sample(1:100, 9), nrow = 3, ncol = 3)
X
# [,1] [,2] [,3]
# [1,] 80 26 29
# [2,] 47 44 49
# [3,] 72 65 81
Wrapping X in .() does what I expect, i.e., it retains its dimensions.
# Wrap `X` in `.()`.
bquote(.(X))
# [,1] [,2] [,3]
# [1,] 80 26 29
# [2,] 47 44 49
# [3,] 72 65 81
However, in the context of a function call, it seems that X is coerced to a
vector. Despite this, R somehow still knows that X is a matrix, as seen in the output of the apply call below.
# Apply a function over rows.
output <- apply(X = X, MARGIN = 1, FUN = function(row) mean(row))
output
# [1] 45.00000 46.66667 72.66667
# Create an expression to apply a function over rows later.
expr <- bquote(apply(X = .(X), MARGIN = 1, FUN = function(row) mean(row)))
expr
# apply(X = c(80L, 47L, 72L, 26L, 44L, 65L, 29L, 49L, 81L), MARGIN = 1,
# FUN = function(row) mean(row))
# Not necessary, but remove `X`.
rm(X, envir = .GlobalEnv)
# Evaluate the expression and compare it with the previous output.
eval(expr) == output
# [1] TRUE TRUE TRUE
How does R know that X is a matrix in the expr expression above?
bquoteis irrelevant here. A simpler example:The argument of the call is a matrix, but
print.defaultdeparses it without attributes.deparsedoes the right thing:The reason is that
deparseuses the"showAttributes"option by default:This character vector is converted by
.deparseOptsto an integer whose bits indicate whether the respective options are turned on or off:The header file
Defn.hin R's sources defines the mapping:If you dig around in
print.c, then you'll find (in the body of functionPrintLanguage) thatprint.defaultuses theDEFAULTDEPARSEoption for language objects. It has theSHOWATTRIBUTESbit turned off, and there is no option for the user to turn it on.Well, I've just asked in the R-devel mailing list (i.e., see here) if
DEFAULTDEPARSEshould be changed to 1093 to match the R level default.