Test if a date is a holiday in r

那年仲夏 提交于 2020-01-03 06:42:10

问题


I have a data set that looks like this:

9/1/2014 00:00:25  
9/1/2014 00:00:28  
9/1/2014 00:00:40  

There are many more observations...

I want to create a column that indicates if a date is a holiday or not , so i used the is.holiday() function. This is my code:

final_uber_4$is_holiday <- is.holiday(final_uber_4$interv) 

The problem is that it returnes 0 for all the observations although I know for sure there are holidays in my data set.


回答1:


I assume you are using the is.holiday function from the chron package. I'd recommend against using that package; the date functions in R have improved since it was written and it isn't needed.

If you want to use is.holiday, you need to provide a list of holidays in the format that chron is expecting. This isn't easy; see this question How to define holidays for is.holiday() chron package in R from 2016 for a discussion.

But if you're providing the list of holidays, you don't need is.holiday. Just use %in%. For example,

holidays <- as.Date(c(NewYears = "2014-01-01", Christmas = "2014-12-25"))
# Add more to the list above...

# Convert your data plus a holiday to POSIXct format:
interv <- as.POSIXct(c("9/1/2014 00:00:25", 
                       "9/1/2014 00:00:28",
                       "9/1/2014 00:00:40",
                       "1/1/2014 00:00:00"), format = "%m/%d/%Y %H:%M:%S")

# Extract the date:
dates <- as.Date(interv)

# Test if you've got a holiday:
dates %in% holidays

This gives me

[1] FALSE FALSE FALSE  TRUE

at the end.



来源:https://stackoverflow.com/questions/54491575/test-if-a-date-is-a-holiday-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!