我对
bquote
如何处理多维项(例如,矩阵)感到困惑
包裹在.()
.
假设我有以下
X
矩阵。
# 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
在
X
中包装 .()
做我所期望的,即它保留其尺寸。
# Wrap `X` in `.()`.
bquote(.(X))
# [,1] [,2] [,3]
# [1,] 80 26 29
# [2,] 47 44 49
# [3,] 72 65 81
但是,在函数调用的上下文中,
X
似乎被强制转换为
向量。尽管如此,R
仍然以某种方式知道 X
是一个矩阵,如下面 apply
调用的输出所示。
# 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
R
怎么知道X
是上面expr
表达式中的矩阵?
bquote
在这里无关紧要。一个更简单的例子:
> expr <- call("is.matrix", matrix(1:4, 2L, 2L))
> expr[[2L]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
> eval(expr)
[1] TRUE
> print(expr)
is.matrix(1:4)
调用的参数是一个矩阵,但是
print.default
在没有属性的情况下对其进行了解析。 deparse
做正确的事:
> writeLines(deparse(expr))
is.matrix(structure(1:4, dim = c(2L, 2L)))
原因是
deparse
默认使用这些deparse选项,包括"showAttributes"
:
> (ctrl <- eval(formals(deparse)[["control"]]))
[1] "keepNA" "keepInteger" "niceNames" "showAttributes"
此字符向量由
.deparseOpts
转换为整数,其 bits 表示相应选项是打开还是关闭。
> .deparseOpts(ctrl)
[1] 1093
Defn.h
解释了映射:
/* deparse option bits: change do_dump if more are added */
#define KEEPINTEGER 1
#define QUOTEEXPRESSIONS 2
#define SHOWATTRIBUTES 4
#define USESOURCE 8
#define WARNINCOMPLETE 16
#define DELAYPROMISES 32
#define KEEPNA 64
#define S_COMPAT 128
#define HEXNUMERIC 256
#define DIGITS17 512
#define NICE_NAMES 1024
/* common combinations of the above */
#define SIMPLEDEPARSE 0
#define DEFAULTDEPARSE 1089 /* KEEPINTEGER | KEEPNA | NICE_NAMES, used for calls */
#define FORSOURCING 95 /* not DELAYPROMISES, used in edit.c */
print.c
中四处挖掘,那么你会发现(在函数 PrintLanguage
的主体中)print.default
使用语言对象的 DEFAULTDEPARSE
选项。它关闭了 SHOWATTRIBUTES
位,用户没有打开它的选项。
好吧,我刚刚在 R-devel 邮件列表中询问是否应将
DEFAULTDEPARSE
更改为 1093 以匹配 R 级别默认值。