这是case_when 方法。首先,我们需要为我们的时期获取一年中的某一天值。北半球天文夏季的开始(6 月 21 日)是第 172天,结束是第 267天(9 月 23 日)。你可以用lubridate::yday("2019-06-21")来做。
然后我们需要对我们的数据框做同样的事情。所以我们得到了你的ts1。我们需要将其转换为data.frame 或tibble 并计算yday:
library(lubridate)
library(dplyr)
ts1 <- seq(ymd('2016-01-01'), ymd('2018-12-31'), '1 day')
ts1 <- tibble(date = (ts1),
day = yday(ts1))
使用sqldf
library(sqldf)
sqldf("select ts1.*, case when (ts1.day >= 172 and ts1.day <= 267)
then 1 else 0 end as TOY
from ts1", method = c("Date", "numeric", "logical")) %>%
as_tibble()
# A tibble: 1,096 x 3
date day TOY
<date> <dbl> <lgl>
1 2016-01-01 1 FALSE
2 2016-01-02 2 FALSE
3 2016-01-03 3 FALSE
4 2016-01-04 4 FALSE
5 2016-01-05 5 FALSE
6 2016-01-06 6 FALSE
7 2016-01-07 7 FALSE
8 2016-01-08 8 FALSE
9 2016-01-09 9 FALSE
10 2016-01-10 10 FALSE
# ... with 1,086 more rows
使用dplyr
ts1 %>%
mutate(TOY = case_when(day >= 172 & day <= 267 ~ "summer",
TRUE ~ "other"))
# A tibble: 1,096 x 3
date day TOY
<date> <dbl> <chr>
1 2016-01-01 1 other
2 2016-01-02 2 other
3 2016-01-03 3 other
4 2016-01-04 4 other
5 2016-01-05 5 other
6 2016-01-06 6 other
7 2016-01-07 7 other
8 2016-01-08 8 other
9 2016-01-09 9 other
10 2016-01-10 10 other
# ... with 1,086 more rows