I'm really wondering why when I keep the last line (sigma) in my function foo1 my plot call stops working BUT when I delete the last line in foo2 the plot call works fine?!
Note: My understanding is that plot should show anywhere in the function like:
foo3 <- function(x = 1:3){; plot(x); return(x); }; foo3()
I need to keep the last line but I also need to plot, is this fixable?
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)
But simply delete the last line of foo1 and plot works fine!
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)