对日期使用 R cut 函数

发布于 2024-12-03 14:55:16 字数 375 浏览 0 评论 0原文

我有一个数据框,提供体育赛事的出席情况

Crowd    matchDate
2345      1993-01-26
4567      1993-08-01
8888      1994-03-02
1298      1994-11-07
9876      1995-09-01 etc

1237      2011-09-09

matchdate 是一个 POSIXct 类

我希望能够根据日期创建一个季节因素,例如每个季节从 8 月 1 日到 7 月 31 日,例如因素 1992/3 将包括日期 1992-08-01 到 1993-07-31

理想情况下,这将是我可以应用于多项分析的函数,不一定具有相同的开始和结束日期

I have a dataframe giving attendances at sports events

Crowd    matchDate
2345      1993-01-26
4567      1993-08-01
8888      1994-03-02
1298      1994-11-07
9876      1995-09-01 etc

1237      2011-09-09

The matchdate is a POSIXct class

I want to be able to create a season factor based on the date such that each season runs from, say, 1st August to 31 July e.g factor 1992/3 would include dates 1992-08-01 to 1993-07-31

ideally it would be a function that I could apply for several analyses, not necessarily with same start and end dates in the year

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

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

发布评论

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

评论(2

很糊涂小朋友 2024-12-10 14:55:16

我的评论的一个例子。

x <- as.Date(1:1000, origin = "2000-01-01")
x <- cut(x, breaks = "quarter") 

然后根据需要重新标记。

labs <- paste(substr(levels(x),1,4), "/", 1:4, sep="")
x <- factor(x, labels = labs)

?cut.POSIXct

休息
割点向量或数字,给出 x 要切割成的区间数或区间规格,一
“秒”、“分钟”、“小时”、“日”、“夏令时日”、“周”、“月”、“季度”
或“年”,可选地前面有一个整数和一个空格,或者后面有
通过“s”。 (对于“日期”对象,仅使用“日”指定间隔,
允许使用“周”、“月”、“季度”和“年”。)

An example of my comment.

x <- as.Date(1:1000, origin = "2000-01-01")
x <- cut(x, breaks = "quarter") 

And then relabel as you please, if necessary.

labs <- paste(substr(levels(x),1,4), "/", 1:4, sep="")
x <- factor(x, labels = labs)

?cut.POSIXct

breaks
a vector of cut points or number giving the number of intervals which x is to be cut into or an interval specification, one
of "sec", "min", "hour", "day", "DSTday", "week", "month", "quarter"
or "year", optionally preceded by an integer and a space, or followed
by "s". (For "Date" objects only interval specifications using "day",
"week", "month", "quarter" and "year" are allowed.)

硬不硬你别怂 2024-12-10 14:55:16

如果您的问题与如何自动生成中断和标签更相关,也许这会有所帮助

DF <- data.frame(matchDate = as.POSIXct(as.Date(sample(5000,100,replace=TRUE), origin="1993-01-01")))

years <- 1992:2011
DF$season <- cut(DF$matchDate, 
  breaks=as.POSIXct(paste(years,"-08-01",sep="")),
  labels=paste(years[-length(years)],years[-length(years)]+1,sep="/"))

If your question is more related to how you automatically generate the breaks and labels, maybe this will help

DF <- data.frame(matchDate = as.POSIXct(as.Date(sample(5000,100,replace=TRUE), origin="1993-01-01")))

years <- 1992:2011
DF$season <- cut(DF$matchDate, 
  breaks=as.POSIXct(paste(years,"-08-01",sep="")),
  labels=paste(years[-length(years)],years[-length(years)]+1,sep="/"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文