查找一周中的哪一天
假设我在 R 中有一个日期,其格式如下。
date
2012-02-01
2012-02-01
2012-02-02
R 中是否有任何方法可以添加另一列,其中包含与日期相关的星期几?数据集非常大,因此手动进行更改是没有意义的。
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
因此,添加天数后,最终会看起来像:
date day
2012-02-01 Wednesday
2012-02-01 Wednesday
2012-02-02 Thursday
这可能吗?任何人都可以向我指出一个可以让我执行此操作的软件包吗? 只是想按日期自动生成日期。
Let's say that I have a date in R and it's formatted as follows.
date
2012-02-01
2012-02-01
2012-02-02
Is there any way in R to add another column with the day of the week associated with the date? The dataset is really large, so it would not make sense to go through manually and make the changes.
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
So after adding the days, it would end up looking like:
date day
2012-02-01 Wednesday
2012-02-01 Wednesday
2012-02-02 Thursday
Is this possible? Can anyone point me to a package that will allow me to do this?
Just trying to automatically generate the day by the date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
编辑: 只是为了展示另一种方式...
POSIXlt
对象的wday
组件是数字工作日(0-6 从星期日开始) 。您可以使用它来对工作日名称的字符向量进行子集化
Edit: Just to show another way...
The
wday
component of aPOSIXlt
object is the numeric weekday (0-6 starting on Sunday).which you could use to subset a character vector of weekday names
使用
lubridate
包和函数wday
:Use the
lubridate
package and functionwday
:查找
?strftime
:Look up
?strftime
:假设您还希望一周从星期一开始(而不是默认的星期日),那么以下内容会很有帮助:
结果是间隔 [0,..,6] 中的天数。
如果您希望间隔为 [1,..7],请使用以下命令:
... 或者:
Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:
The result is the days in the interval [0,..,6].
If you want the interval to be [1,..7], use the following:
... or, alternatively:
这应该可以解决问题
This should do the trick
JStrahl
format(as.Date(df$date),"%w")
的表单注释,我们得到当天的数字:as.numeric(format(as.Date("2016-05-09"),"%w"))
form comment of JStrahl
format(as.Date(df$date),"%w")
, we get number of current day :as.numeric(format(as.Date("2016-05-09"),"%w"))