我正在构建一个使用 flextable 创建表格的函数。我想指定颜色渐变,但有些值不适用。我希望这些 NA 值(更改为“-”)是透明的。该数据集包含某人对特定年份的评级(示例中为 rating_2023),但我希望代码能够灵活地适应不同的年份,而不是硬编码特定年份。
由于某种原因,当我想检测某个值是否为 NA 时,flextable 无法理解
.
、{{}}
或 enquo()
。
具体来说,这是我的示例数据:
library(dplyr)
library(flextable)
library(scales)
sample_data <- tibble(emp_id = c(1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4, 4),
survey_period = c("q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1"),
rating_2023 = c(100, 90, 40, NA,
-10, -20, 0, 10,
80, -10, NA, NA,
90, 50, -20, NA))
当我在
i = ~is.na(rating_2023),
中的 rating_2023 中进行硬编码时,我的函数就可以工作了
make_table <- function(data, time_period){
gen_rating <- paste0("rating_", time_period)
gradient <- col_numeric(
palette = c("red", "transparent", "green"),
domain = c(-100, 0, 100)
)
data %>%
flextable() %>%
colformat_num(na_str = " - ") %>%
bg(
bg = gradient,
j = 3,
part = "body"
) %>%
bg(
bg = "transparent",
i = ~is.na(rating_2023),
j = gen_rating
)
}
make_table(sample_data, time_period = "2023")
但是当我尝试通过管道输入对象时,它会产生
Error in eval(as.call(f[[2]]), envir = data) : object 'gen_rating' not found
。当我尝试使用 .
时,我也得到了类似的答案:
make_table <- function(data, time_period){
gen_rating <- paste0("rating_", time_period)
gradient <- col_numeric(
palette = c("red", "transparent", "green"),
domain = c(-100, 0, 100)
)
data %>%
flextable() %>%
colformat_num(na_str = " - ") %>%
bg(
bg = gradient,
j = 3,
part = "body"
) %>%
bg(
bg = "transparent",
i = ~is.na({{gen_rating}}),
j = gen_rating
)
}
make_table(sample_data, time_period = "2023")
为什么这不起作用?有没有解决方案,或者我今年被迫进行硬编码?
使用
as.formula()
或 reformulate()
- 还有一个带有“rlang”的解决方案,但我不记得如何编码:
library(dplyr)
library(flextable)
library(scales)
sample_data <- tibble(
emp_id = c(
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4, 4
),
survey_period = c(
"q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1",
"q4", "q3", "q2", "q1"
),
rating_2023 = c(
100, 90, 40, NA,
-10, -20, 0, 10,
80, -10, NA, NA,
90, 50, -20, NA
)
)
make_table <- function(data, time_period) {
gen_rating <- paste0("rating_", time_period)
gradient <- col_numeric(
palette = c("red", "transparent", "green"),
domain = c(-100, 0, 100)
)
data %>%
flextable() %>%
colformat_num(na_str = " - ") %>%
bg(
bg = gradient,
j = 3,
part = "body"
) %>%
bg(
bg = "transparent",
i = reformulate(sprintf("is.na(`%s`)", gen_rating)),
j = gen_rating
)
}
make_table(sample_data, time_period = "2023")