我正在嘗試在制作時間序列圖的函式中使用雙大括號,盡管閱讀了有關雙大括號通常如何作業的
uj5u.com熱心網友回復:
雙花括號適用于未加引號的變數名稱。將變數名稱作為字串,使用aes_string,另見此處。
suppressPackageStartupMessages({
library(dplyr)
library(ggplot2)
library(lubridate)
})
#Sample data
test <- tibble(Week = seq(as.Date("2014/09/04"), by = "week", length.out = 8),
Month = ymd(rep('2014-09-01', 4), rep('2014-10-01', 4)),
Week_score = c(2, 3, 4, 6, 5, 7, 8, 9),
Month_score = c(15, NA, NA, NA, 29, NA, NA, NA))
#My function
make_time_plot <- function(data, time_period = c("Week", "Month")) {
time_period <- match.arg(time_period)
time_period_score <- paste0(time_period, "_score")
data %>%
ggplot(aes_string(x = time_period, y = time_period_score))
geom_line()
}
#make_time_plot(data = test, time_period = "Month")
make_time_plot(data = test, time_period = "Week")

由reprex 包創建于 2022-04-02 (v2.0.1)
uj5u.com熱心網友回復:
這里發生了幾件事。{{}}處理未參考的變數,并且不能與字串混合和匹配。
例如:當你寫的時候mtcars %>% select(hp),你不需要寫"hp"。這是由于“資料屏蔽”,這個程序使 R 理解這hp是一個變數mtcars,而不是你的環境中的變數。這不是使此代碼作業的程序:
# Defining an env-variable
cyl <- 1000
# Referring to a data-variable
dplyr::summarise(mtcars, mean(cyl))
#> mean(cyl)
#> 1 6.1875
由reprex 包創建于 2022-04-02 (v2.0.1)
如何修復你的功能
有更簡單的方法來修復您的功能,而無需使用{{}},但如果您想了解如何使用,{{}}我在此處提供了一個示例。
make_time_plot <- function(data, time_period) {
time_period_score <- paste0(rlang::as_name(enquo(time_period)), "_score")
data %>%
ggplot(
aes(
x = {{time_period}},
y = .data[[time_period_score]]
)
)
geom_line()
}
make_time_plot(data = test, time_period = Week)

由reprex 包創建于 2022-04-02 (v2.0.1)
我更改了以下內容:
- 由于您要將字串粘貼到
time_period, 并且time_period是未參考的變數,因此您需要使用rlang::as_name(enquo(time_period)). - 由于
time_period_score是一個字串,因此您需要將其aes()作為字串提供。由于time_period不是字串,所以不能使用aes_string(),所以我使用.data代詞 with.data[[time_period_score]]。
{{}} 您可以在此處找到更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456813.html
上一篇:如何用雙大括號過濾日期?
下一篇:計算兩個時間戳之間的不同日期
