與我關于 ggplot 中雙大括號的其他問題類似,我也在努力使用帶有過濾日期的雙大括號。在此功能中,用戶可以指定一個時間段(周、月),然后該功能根據相應的時間段進行過濾。例如,選擇“月”應該使函式只關注Month和Month_score列。但是,它不斷失敗并提供不正確的輸出:
這是我的示例資料以及我進行的 2 次嘗試:
#Sample data
library(dplyr)
library(lubdridate)
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))
嘗試 1 - 不洗掉任何列(這是不正確的):
date_filter <- function(data, time_period = c("Week", "Month"), start_date = NA_Date_) {
data %>%
filter({{time_period}} > start_date)
}
date_filter(data = test, time_period = "Week", start_date = '2014-09-06')
嘗試 2:我明確指出 start_date 是一個日期,但出現以下錯誤
date_filter <- function(data, time_period = c("Week", "Month"), start_date = NA_Date_) {
data %>%
filter({{time_period}} > as.Date(start_date))
}
date_filter(data = test, time_period = "Week", start_date = '2014-09-06')
uj5u.com熱心網友回復:
{{}}旨在用于未加引號的變數名,而不是字串。
呼叫函式時洗掉""from ,它可以作業:time_period
date_filter <- function(data, time_period, start_date = NA_Date_) {
data %>%
filter({{time_period}} > as.Date(start_date))
}
date_filter(data = test, time_period = Week, start_date = '2014-09-06')
#> # A tibble: 7 × 4
#> Week Month Week_score Month_score
#> <date> <date> <dbl> <dbl>
#> 1 2014-09-11 2014-09-01 3 NA
#> 2 2014-09-18 2014-09-01 4 NA
#> 3 2014-09-25 2014-09-01 6 NA
#> 4 2014-10-02 2014-10-01 5 29
#> 5 2014-10-09 2014-10-01 7 NA
#> 6 2014-10-16 2014-10-01 8 NA
#> 7 2014-10-23 2014-10-01 9 NA
由reprex 包創建于 2022-04-02 (v2.0.1)
rlang 有一篇不錯的文章,我建議大家在使用{{}}.
為什么time_period = "Week"在第一個函式中起作用而在另一個函式中不起作用?
因為{{time_period}}被解釋為字串,而不是變數Week。您實際上是在嘗試"Week" > "2014-09-06"在第一個函式(始終為TRUE)和"Week" > as.Date("2014-09-06")第二個函式(這使得 R 想要轉換"Week"為日期,因此出現錯誤)中進行比較。
uj5u.com熱心網友回復:
如果我們想傳遞帶引號或不帶引號的,則轉換為symwithensym
date_filter <- function(data, time_period = c("Week", "Month"),
start_date = NA_Date_) {
time_period <- rlang::ensym(time_period)
data %>%
filter(!!time_period > start_date)
}
-測驗
> date_filter(data = test, time_period = "Week", start_date = '2014-09-06')
# A tibble: 7 × 4
Week Month Week_score Month_score
<date> <date> <dbl> <dbl>
1 2014-09-11 2014-09-01 3 NA
2 2014-09-18 2014-09-01 4 NA
3 2014-09-25 2014-09-01 6 NA
4 2014-10-02 2014-10-01 5 29
5 2014-10-09 2014-10-01 7 NA
6 2014-10-16 2014-10-01 8 NA
7 2014-10-23 2014-10-01 9 NA
>
> date_filter(data = test, time_period = Week, start_date = '2014-09-06')
# A tibble: 7 × 4
Week Month Week_score Month_score
<date> <date> <dbl> <dbl>
1 2014-09-11 2014-09-01 3 NA
2 2014-09-18 2014-09-01 4 NA
3 2014-09-25 2014-09-01 6 NA
4 2014-10-02 2014-10-01 5 29
5 2014-10-09 2014-10-01 7 NA
6 2014-10-16 2014-10-01 8 NA
7 2014-10-23 2014-10-01 9 NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456812.html
上一篇:如何在PHP中為時間添加奇數天?
