【发布时间】:2020-05-21 05:29:50
【问题描述】:
我真的很想知道为什么当我在函数 foo1 中保留最后一行 (sigma) 时,我的 plot 调用停止工作,但是当我删除 foo2 中的最后一行时,plot 调用工作好吗?!
注意: 我的理解是 plot 应该显示在函数中的任何位置,例如:
foo3 <- function(x = 1:3){; plot(x); return(x); }; foo3()
我需要保留最后一行,但我还需要绘图,这可以修复吗?
library(lme4)
library(emmeans)
h <- read.csv('https://raw.githubusercontent.com/hkil/m/master/h.csv')
h$year <- as.factor(h$year)
m <- lmer(scale~ year*group + (1|stid), data = h)
foo1 <- function(fit, plot = T){
vc <- VarCorr(fit)
f <- as.formula(bquote(pairwise ~ .(terms(fit)[[3]])))
ems <- emmeans(fit, f, infer = c(T, T))
if(plot) plot(ems)
## Why having this line prevents plotting?
sigma <- sqrt(sum(as.numeric(c(attr(vc[[1]], "stddev"), attr(vc, "sc")))^2))
}
###### EXAMPLE: Will NOT plot !!!
foo1(m, plot = T)
但只需删除foo1 的最后一行,情节就可以正常工作了!
foo2 <- function(fit, plot = T){
f <- as.formula(bquote(pairwise ~ .(terms(fit)[[3]])))
ems <- emmeans(fit, f, infer = c(T, T))
if(plot) plot(ems)
}
###### EXAMPLE: NOW plots fine !!!
foo2(m, plot = T)
【问题讨论】:
标签: r function class attributes s4