R 更快的工作日方法

发布于 2025-01-13 16:23:10 字数 411 浏览 4 评论 0原文

您好,我正在尝试将给定的日期转换为各自的工作日,我有一个百万行的数据集,并且我仅使用其中包含日期的列。

我目前正在使用

ifelse(wday(data$started_at)==1,7,wday(data$started_at)-1)

“我希望星期一显示为 1,星期日显示为 7”,但是,我并不在意,我宁愿有一个更快的程序。

作为您使用的试用数据:

   x<- rep("2022-02-01 00:00:04",1000000)

这是我目前拥有的数据,

   ifelse(wday(x)==1,7,wday(x)-1)

我正在努力使其更快,目前在我的计算机上需要 17 秒。

Hi I am trying to convert the given dates into their respective weekdays, I have a data set of million lines, and I am only using the column with the dates in it.

I am currently using

ifelse(wday(data$started_at)==1,7,wday(data$started_at)-1)

I want Monday to be indicated as 1 and Sunday as 7, however, I do not really care, I would much rather have a faster program.

As trial data you use :

   x<- rep("2022-02-01 00:00:04",1000000)

This is what I currently have

   ifelse(wday(x)==1,7,wday(x)-1)

I am trying to make it much faster, it currently takes 17second on my computer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东走西顾 2025-01-20 16:23:10

lubridate::wday 中有一个名为 week_start 的参数:

x<- "2022-02-01 00:00:04"
wday(x, week_start = 1)

There is an argument in lubridate::wday called week_start:

x<- "2022-02-01 00:00:04"
wday(x, week_start = 1)
忘你却要生生世世 2025-01-20 16:23:10

这里不需要额外的 ifelse 和调用 wday 两次。奇怪的是,下面的代码稍微快一些,并给出一个整数,而不是 wday 中的默认数字。

x <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 1e7, replace = T)

z <- c(7L, 1:6)

bench::mark(
  x = wday(x, week_start = 1),
  y = z[wday(x)]
)[c(3,5,7,9)]
    median mem_alloc n_itr total_time
  <bch:tm> <bch:byt> <int>   <bch:tm>
1       1s     534MB     1         1s
2    879ms     534MB     1      879ms

The extra ifelse and calling wday twice is not needed here. Curiously, the following is slightly faster, and gives an integer instead of the default numeric from wday.

x <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 1e7, replace = T)

z <- c(7L, 1:6)

bench::mark(
  x = wday(x, week_start = 1),
  y = z[wday(x)]
)[c(3,5,7,9)]
    median mem_alloc n_itr total_time
  <bch:tm> <bch:byt> <int>   <bch:tm>
1       1s     534MB     1         1s
2    879ms     534MB     1      879ms
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文