首页 > 解决方案 > R:未找到自定义函数中的对象以用于特定用途

问题描述

我遇到了 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, face = "bold", colour = "black"),
            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, label = "{pval.label(pvalue$p)}", bracket.size = 1, size = 4) 它说找不到对象“pvalue”。但是,如果我在函数之外创建这个对象并将它放在 R 环境中,它会很好地工作!

怎么解释?以及如何处理?

谢谢,奥利维尔

标签: rfunctionggplot2ggpubr

解决方案


推荐阅读