我遇到了R的问题(以及它在处理对象方面的众所周知的严谨性...):我编写了一个自定义函数来绘制ggplots中的点图,并使用方括号添加自定义p值。问题不是情节(它运作良好...),而是处理对象和函数:我无法使用在函数内部创建的对象。一些代码来解释:
pval.label <- function(p)
{
if (p < 0.001) { return("p<0.001") }
else { return(paste0("p = ",round(p,digits = 2))) }
}
dot_plot <- function(data,var,endpoint,title,ylab)
{
endpoint = deparse(substitute(endpoint))
var = deparse(substitute(var))
df = data.frame(var = data[[var]],endpoint = data[[endpoint]])
pvalue = compare_means(data = df,formula = var ~ endpoint)
pvalue <- pvalue %>% mutate(y.position = 120*(max(df$var)/100))
plot =
ggplot(df,aes(x=endpoint,y=var)) +
labs(title = title,y = ylab,x="") +
geom_dotplot(binaxis='y',stackdir='center',stackratio=1.7,binwidth = .8,show.legend = F,aes(fill = endpoint,color = endpoint)) +
stat_summary(fun=median,geom="crossbar",lwd=.5,width=.7,col="black",show.legend=F) +
scale_fill_manual(values=c("#2d419b","#ee2025")) +
scale_color_manual(values=c("#2d419b","#ee2025")) +
theme_classic() +
theme(text = element_text(family = "sans",face = "bold"),plot.title = element_text(size = 14,hjust = .5,lineheight = 1.5),axis.text = element_text(size = 12,face = "bold",colour = "black"),axis.title = element_text(size = 14,axis.line = element_line(size = 1),axis.ticks = element_line(size = 1),axis.ticks.length = unit(5,"pt")) +
stat_pvalue_manual(pvalue,label = "{pval.label(pvalue$p)}",bracket.size = 1,size = 4)
plot
}
问题在于此行:
stat_pvalue_manual(pvalue,size = 4)
它说找不到对象“ pvalue”。但是,如果我在函数外部创建此对象并将其放在R环境中,则效果很好!!
该如何解释?以及如何处理呢?
谢谢, 奥利维尔