计算R中2个日期之间的平日数 [英] Calculate the number of weekdays between 2 dates in R

查看:137
本文介绍了计算R中2个日期之间的平日数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个R函数来计算两个日期之间的平日数。例如,Nweekdays('01 / 30/2011','02/04/2011')将等于5。

I'm trying to write an R function to calculate the number of weekdays between two dates. For example, Nweekdays('01/30/2011','02/04/2011') would equal 5.

这个问题。谢谢!

/ edit:@J。温彻斯特的答案很棒,但是我想知道有没有人可以想到一种向量化方式的方法,以便它可以在两列的日期上工作。谢谢!
/编辑2:再次感谢

/edit: @J. Winchester's answer is great, but I was wondering if anyone could think of a way to vectorize this, so that it'll work on 2 columns of dates. Thanks! /edit 2: Thanks again!

推荐答案

Date1 <- as.Date("2011-01-30")
Date2 <- as.Date("2011-02-04")    
sum(!weekdays(seq(Date1, Date2, "days")) %in% c("Saturday", "Sunday"))

编辑:让 Vectorize :)

Dates1 <- as.Date("2011-01-30") + rep(0, 10)
Dates2 <- as.Date("2011-02-04") + seq(0, 9)
Nweekdays <- Vectorize(function(a, b) 
  sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")))
Nweekdays(Dates1, Dates2)

这篇关于计算R中2个日期之间的平日数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆