如何在 ggtitle 中使用 rmarkdown 内联代码

How can I use rmarkdown inline code within a ggtitle

我正在尝试使用内联代码让我的样本大小出现在我的绘图标题中,这样我就可以避免每次使用此代码块时忘记更新 (N = 128) 的错误。目前 R 无法识别我在代码的最后一行中尝试使用的内联代码“(N = r nrow(df))”。

library(Rmisc) # for summarySE function

# create descriptive stats for bar plot
    df <- subset(mtcars, select = c(mpg, cyl))
    dfc <- summarySE(df, measurevar = "mpg", groupvars = c("cyl"))

# bar plot
ggplot(dfc, aes(x=cyl, y=mpg)) + # insert variables
      geom_bar(aes(fill=cyl), # essential for bar coloring
               position=position_dodge(),
               stat="identity", colour="black", size=0) + 
      geom_errorbar(aes(ymin= mpg - se, ymax= mpg + se), 
                    size=.4, width=.1, position=position_dodge(.9)) + 
      ggtitle("(N = `r nrow(df)`)")  ### THIS IS THE LINE I WANT TO WORK ###

提前感谢您的帮助。

您可以通过 paste 函数执行此操作,如下所示:

n_value <- paste("( N = ", nrow(dat), ")")
ggtitle(paste0(n_value))

下面会做 + 给你逗号格式的数字,如果你进入数千+。

sprintf("( N = %s )", scales::comma(nrow(dat)))

sprintf("( N = %s )", scales::comma(nrow(ggplot2movies::movies)))
## [1] "( N = 58,788 )"