R中的周范围输出 [英] Week Range Output in R

查看:68
本文介绍了R中的周范围输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个R脚本,该脚本将在数据框中显示工作日范围和日期所属的星期.

I'm working on an R script that would display the weekday range and week the dates fall in, in a data frame.

我要显示的输出

--------------------------------------------------
 DateRange                    | Week                            
--------------------------------------------------
 1/7/2018  - 1/13/2018        |   2
--------------------------------------------------
 1/14/2018  - 1/20/2018       |   3
--------------------------------------------------
 1/21/2018  - 1/26/2018       |   4
--------------------------------------------------

library(data.table)
dd <- seq(as.IDate("2018-01-01"), as.IDate("2018-04-10"), 1)
dt <- data.table(i = 1:length(dd),
                 day = dd,
                 weekday = weekdays(dd),
                 day_rounded = round(dd, "weeks"))
## Now let's add the weekdays for the "rounded" date
dt[ , weekday_rounded := weekdays(day_rounded)]
## This seems to make internal sense with the "week" calculation
dt[ , weeknumber := week(day)]
dt$weekday_rounded <- NULL
dt$day_rounded <- NULL
dt

推荐答案

如果您有一些带有 day 列和其他任意列的表 dt ,则可以添加一次调用 data.table 中的 i weekday weeknumber WeekRange :

If you have some table dt with a day column and other arbitrary columns, you can add the i, weekday, weeknumber and WeekRange in a single call in data.table:

dt[, ':='(
  i = .I,
  weekday = weekdays(day),
  WeekRange = paste(min(day), max(day), sep = ' - ')
), .(weeknumber = week(day))]

此方法的工作方式是将天按周数或周(天)分组,然后将这些日期中的最小日期和最大日期粘贴在一起,以创建每周的日期范围.

The way this works is to group the days by weeknumber, or week(day), and then to paste the min date and max date in those groups together to create a date range for every week.

这是一个模拟表,可供您尝试:

Here's a mock table to experiment with:

n <- 100
dt <-
  data.table(
    day = seq.Date(as.Date('2018-01-01'), by = 'day', length.out = n),
    a = runif(n),
    b = runif(n)
  )

这篇关于R中的周范围输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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