简体   繁体   English

年 - 周在r中增加一周

[英]Year-Week add a week in r

I have a dataframe with a column containing Date and time, and I have created a new column containing Year-Week with this formula, 我有一个包含日期和时间的列的数据框,我创建了一个包含此公式的Year-Week的新列,

Path     LogTime
HJH      2015-06-19 01:57:11
GTF      2015-07-31 08:23:34
R        2015-07-21 11:52:31

Path2$Week<-strftime(Path2$LogTime,format="%Y-%W",tz="CET")
Path     LogTime                Week
HJH      2015-06-19 01:57:11    2015-24
GTF      2015-07-31 08:23:34    2015-30
R        2015-07-21 11:52:31    2015-29

I now want to add another week to it, so instead of it saying 我现在想再添加一周,所以不要说它

Path     LogTime                Week       NEW Week
HJH      2015-06-19 01:57:11    2015-24    2015-25
GTF      2015-07-31 08:23:34    2015-30    2015-31
R        2015-07-21 11:52:31    2015-29    2015-30

How can I do this in R? 我怎么能在R中这样做? I have trouble finding my way in the maze of the dates in R 我很难在R的日期迷宫中找到自己的方式

Path$New.Week <- strftime(as.Date(Path$LogTime)+7, "%Y-%W", tz="CET")
   Path            LogTime    Week New.Week
1  HJH 2015-06-19 01:57:11 2015-24  2015-25
2  GTF 2015-07-31 08:23:34 2015-30  2015-31
3    R 2015-07-21 11:52:31 2015-29  2015-30

As mentioned in the comments by @DavidArenburg, if the LogTime column is in any proper date format like POSIXct as it appears to be in your example, and not a string or factor, you can save an operation with: 正如@DavidArenburg的评论中所提到的,如果LogTime列处于任何正确的日期格式,如POSIXct因为它似乎在您的示例中,而不是字符串或因子,您可以使用以下命令保存操作:

Path$NewWeek <- strftime(Path$LogTime + 60*60*24*7, format = "%Y-%W", tz = "CET")

As is often the case with R, "There is a package for that". 与R的情况一样,“有一个包”。 I recommend lubridate . 我推荐lubridate This chapter covers all the usual tasks. 本章介绍了所有常规任务。 This turns your task into one line without losing information: 这会将您的任务变为一行而不会丢失信息:

library(lubridate)   
data$New.Week <- data$LogTime + weeks(1)

By stripping the day/time out of LogTime, you are losing lots of information. 通过剥离LogTime的日期/时间,您将丢失大量信息。 And by turning LogTime into type character, you are asking for trouble when you want to perform math operations. 通过将LogTime转换为类型字符,当您想要执行数学运算时,您会遇到麻烦。

However, I bet you are trying to get YYYY-WW because you are trying to perform some summaries or something. 但是,我打赌你试图获得YYYY-WW,因为你正试图执行一些摘要或其他东西。 If this is the case, you don't even need to calculate YYYY-WW. 如果是这种情况,您甚至不需要计算YYYY-WW。 Just use group_by from dplyr (which is included in tidyverse ). 只需使用dplyr group_by (包含在tidyverse )。

library(tidyverse)
data %>%
  group_by(year(LogTime),week(LogTime)) %>%
  summarise(count_by_week = n())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM