fun = R 中汇总函数的参数

fun= argument of summary function in R

我正在使用 R Data Analysis Examples: Ordinal Logistic Regression 作为进行顺序逻辑回归的指南(最终在 python 中使用 rpy2 接口)。

在测试比例赔率假设的步骤中,他们使用以下公式创建了 table 预测估计值:

(s <- with(dat, summary(as.numeric(apply) ~ pared + public + gpa, fun=sf)))

我注意到的一件事是,如果 fun 是大写的,fun = 参数的行为是不同的。为了解原因,我查看了此处的源代码:summary.R source,但只找到了 FUN =

根据加州大学洛杉矶分校网站(在上面的 link 中):"When R sees a call to summary with a formula argument, it will calculate descriptive statistics for the variable on the left side of the formula by groups on the right side of the formula and will return the results in a nice table. By default, summary will calculate the mean of the left side variable... However, we can override calculation of the mean by supplying our own function, namely sf to the fun= argument. The final command asks R to return the contents to the object s, which is a table."

我明白这是在做什么,但我不确定参数 fun = 在源代码方面的位置(FUN 似乎是默认值,给出了公式并忽略函数 sf)。这个覆盖在哪里?这实际上记录在某个地方吗?如果是这样,在哪里,因为它显然不在帮助文档中。这是我第一次看R源代码,所以我承认我一无所知。

我之所以深入研究这个是因为rpy2中的行为与R中的行为不一致。在R中,fun =FUN =都会产生输出,但在rpy2中,只有FUN = 产生输出; fun = 抛出 RRuntimeError: Error in as.character(substitute(fun)) : cannot coerce type 'closure' to vector of type 'character'

的错误

因此,需要深入研究源代码以弄清楚为什么它没有按预期工作。

编辑

成功和失败的 python 行分别是(我在 R 中创建了一个名为 gms.test 的包,其中包含 function/closure sf):

from rpy2.robjects import pandas2ri
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
pandas2ri.activate()
gms = importr("gms.test")
hmisc = importr('Hmisc')
base = importr('base', robject_translations={'with': '_with'})
stats = importr('stats', robject_translations={'format_perc': '_format_perc'})

r_consult_case_control = pandas2ri.py2ri(consult_case_control)
formula = stats.as_formula('es_score ~ n + raingarden + consult_case')

formula.getenvironment()['es_score'] = r_consult_case_control.rx2('es_score')
formula.getenvironment()['n'] = r_consult_case_control.rx2('n')
formula.getenvironment()['raingarden'] = r_consult_case_control.rx2('raingarden')
formula.getenvironment()['consult_case'] = r_consult_case_control.rx2('consult_case')

# succeeds:
base._with(r_consult_case_control, ro.r.summary(formula, FUN=gms.sf))

# fails with given error:
base._with(consult_case_control, ro.r.summary(formula, fun=gms.sf))

请注意,调试此代码不是我在这个问题中的意图。我只是想看看 R 中的 fun 覆盖在做什么。

获取源码很容易。根据 how to view R source,我只是 运行 getAnywhere(summary.formula) 并得到相关代码块:

if (length(fun)) {
    if (length(de <- deparse(fun)) == 2) {
        de <- as.list(fun)
        de <- as.character(de[[length(de)]])
        funlab <- if (de[1] == "apply") 
          de[length(de)]
        else de[1]
    }
    else funlab <- as.character(substitute(fun))
}

因此,如果未使用默认值 fun,它会尝试转换为字符向量,这就是为什么我不断收到闭包强制错误的原因。在 R 中,我可以重新创建错误,只需执行 as.character(sf) ...(FUN,顺便说一句,这是一条红鲱鱼,因为我们不是 fun 的任何参数都具有相同的行为)。哎呀,这确实不好玩!