【发布时间】:2019-05-04 06:53:03
【问题描述】:
我正在尝试编写一个自定义函数,我想在 ggplot2 绘图字幕中显示效果大小估计及其置信区间。我正在使用plotmath 正确显示希腊字母和其他数学符号。
这就是我想要的两种字幕的样子-
为了实现这一点,我编写了一个简单的函数——
# set up
set.seed(123)
library(tidyverse)
library(cowplot)
# creating a fictional dataframe with effect size estimate and its confidence
# intervals
effsize_df <- tibble::tribble(
~estimate, ~conf.low, ~conf.high,
0.25, 0.10, 0.40
)
# function to prepare subtitle
subtitle_maker <- function(effsize_df, effsize.type) {
if (effsize.type == "p_eta") {
# preparing the subtitle
subtitle <-
# extracting the elements of the statistical object
base::substitute(
expr =
paste(
eta["p"]^2,
" = ",
effsize,
", 95% CI",
" [",
LL,
", ",
UL,
"]",
),
env = base::list(
effsize = effsize_df$estimate[1],
LL = effsize_df$conf.low[1],
UL = effsize_df$conf.high[1]
)
)
} else if (effsize.type == "p_omega") {
# preparing the subtitle
subtitle <-
# extracting the elements of the statistical object
base::substitute(
expr =
paste(
omega["p"]^2,
" = ",
effsize,
", 95% CI",
" [",
LL,
", ",
UL,
"]",
),
env = base::list(
effsize = effsize_df$estimate[1],
LL = effsize_df$conf.low[1],
UL = effsize_df$conf.high[1]
)
)
}
# return the subtitle
return(subtitle)
}
请注意,条件语句的代码只有一行不同:eta["p"]^2(如果是"p_eta")或omega["p"]^2(如果是"p_omega"),其余代码相同。我想重构这段代码以避免这种重复。
我不能有条件地将eta["p"]^2 和omega["p"]^2 分配给函数体中的不同对象(比如说effsize.text <- eta["p"]^2),因为R 会抱怨找不到对象eta 和omega在环境中。
我该怎么做?
---------- 后记---------- ----------------
以下是用于创建上面显示的组合图的代码-
# creating and joining two plots (plot is shown above)
cowplot::plot_grid(
# plot 1
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_blank() +
labs(
subtitle = subtitle_maker(effsize_df, "p_omega"),
title = "partial omega"
),
# plot 2
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_blank() +
labs(
subtitle = subtitle_maker(effsize_df, "p_eta"),
title = "partial eta"
),
labels = c("(a)", "(b)"),
nrow = 1
)
【问题讨论】: