简体   繁体   English

使用`timeDate`指示日期

[英]Make indicator for date using `timeDate`

I have a number of dates for which I would like to make an indicator variable for. 我想为指标设置多个日期。 The problem is that I am having difficulty making this happen in R using timeDate . 问题是我很难使用timeDateRtimeDate这一点。 Here is a toy example 这是一个玩具的例子

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

I would like to add an indicator for New Years Day called is_new_year . 我想添加一个称为is_new_year元旦指标。

I tried the following 我尝试了以下

df %>% rowwise() %>% 
  mutate(is_new_year = ifelse(USNewYearsDay(year = year(date)) == date,1,0))

and got the error 并得到了错误

Error in mutate_impl(.data, dots) : Evaluation error: comparison (1) is possible only for atomic and list types. mutate_impl(.data,点)中的错误:评估错误:比较(1)仅适用于原子类型和列表类型。

What should I do to get 我应该怎么做才能得到

  date          is_new_year
  <date>         <int>
1 2010-12-31       0
2 2011-01-01       1
3 2011-01-02       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

Heres an solution: 这是一个解决方案:

# 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

with the output: 输出:

> 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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM