我有一些日期,我想为其制作一个指标变量。问题是我在R
使用timeDate
时遇到困难。这是一个玩具示例
library(timeDate)
library(lubridate)
library(tidyverse)
>df <- tribble(
~date,
"2010-12-31",
"2011-01-01",
"2011-01-02") %>%
mutate(date = ymd(date))
> df
# A tibble: 3 x 1
date
<date>
1 2010-12-31
2 2011-01-01
3 2011-01-02
我想为新年添加一个名为is_new_year
的指标。
我尝试了以下
df %>% rowwise() %>%
mutate(is_new_year = ifelse(USNewYearsDay(year = year(date)) == date,1,0))
并收到错误
mutate_impl(.data,dots)中的错误:评估错误:比较(1)仅适用于原子和列表类型。
我该怎么做才能获得
date is_new_year
<date> <int>
1 2010-12-31 0
2 2011-01-01 1
3 2011-01-02 0
答案 0 :(得分:0)
df%>%mutate(is.newyear=as.numeric(as.Date(paste0(year(date),"-1-1"))==date))
# A tibble: 3 x 2
date is.newyear
<date> <dbl>
1 2010-12-31 0
2 2011-01-01 1
3 2011-01-02 0
答案 1 :(得分:0)
这是一个解决方案:
# dummy dates
x <- seq(as.Date("1900-01-01"), as.Date("2018-12-31"), by = "day")
# first date of year
first <- subset(x, format(as.Date(x),"%m")==12 & format(as.Date(x),"%d")==31)+1
# find if df dates == first date of year
find <- df$date %in% first
df$find <- ifelse(find == TRUE,1,0)
df
输出:
> df
# A tibble: 3 x 2
date find
<date> <dbl>
1 2010-12-31 0
2 2011-01-01 1.00
3 2011-01-02 0