R-时间变量和日期的条件运算 [英] R - Conditional operations on time variables and dates
问题描述
假设,我有下面的数据框,并且要对最后一个变量 HMS
做一些操作。
目的是创建一个新变量,假设 TimeStampNew
并指定第二天(如果观察值在 17:30:00之后)
。当观察值指示无值时('NA'
),则应使用同一日期的 TimeStamp
。
Assumed, I have the dataframe below and want to do some operations on the last variable HMS
.
The aim is to create a new variable, lets say TimeStampNew
and assign the next day if the observation is after 17:30:00
of the day. When the observation indicates no value ('NA'
), then the TimeStamp
of the same date should be used.
问题是,要从类字符转换 HMS
变量,采用允许条件的格式。我已经检查了chron-package或将其转换为 POSIXct
类型的对象作为可能的选择。
The problem is, to convert the HMS
-variable from the class character in a format allowing for conditions. I already checked the chron-package or converting it to a object of type POSIXct
as possible alternatives.
我已经在这篇文章中问过类似的问题: R-字符变量 weekday的条件并以特殊的日期代替在数据框中。
我已经尝试通过 dplyr
包的某些操作来解决该问题,如上面提到的帖子中所建议。但是,由于时间格式复杂,我没有收到所需的解决方案。
A similar question I already asked in this post: R - Condition on character variable "weekday" and replace with special "date" in a data frame .
I already tried to solve the issue with some operations of the dplyr
package as suggested in the post mentioned above. However, I didn't receive the desired solution due to the tricky time format.
有人对这个问题有解决方案吗?!
Has anybody an solution proposal to this question?!
谢谢!
TimeStamp HMS
1 2010-02-22 19:55:00
2 2012-10-10 07:53:00
3 2012-10-24 07:55:00
4 2013-07-15 08:14:00
5 2013-07-24 08:23:00
6 2013-12-02 10:00:00
7 2012-02-23 07:56:00
8 2012-03-06 08:45:00
9 2013-09-15 19:54:00
10 2007-03-28 NA
11 2007-08-09 NA
12 2008-08-07 NA
推荐答案
使用 difftime
和 ifelse
语句:
df1$TimeStamp <- as.Date(df1$TimeStamp, format = "%Y-%m-%d")
df1$TimeStampNew <- ifelse(
difftime(as.POSIXct(df1$HMS, format = "%H:%M:%S"),
as.POSIXct("17:30:00", format = "%H:%M:%S")) > 0,
as.character(df1$TimeStamp + 1),
as.character(df1$TimeStamp))
df1$TimeStampNew[is.na(df1$HMS)] <- as.character(df1$TimeStamp[is.na(df1$HMS)])
它产生的数据框:
> df1
TimeStamp HMS TimeStampNew
1 2010-02-22 19:55:00 2010-02-23
2 2012-10-10 07:53:00 2012-10-10
3 2012-10-24 07:55:00 2012-10-24
4 2013-07-15 08:14:00 2013-07-15
5 2013-07-24 08:23:00 2013-07-24
6 2013-12-02 10:00:00 2013-12-02
7 2012-02-23 07:56:00 2012-02-23
8 2012-03-06 08:45:00 2012-03-06
9 2013-09-15 19:54:00 2013-09-16
10 2007-03-28 <NA> 2007-03-28
11 2007-08-09 <NA> 2007-08-09
12 2008-08-07 <NA> 2008-08-07
这篇关于R-时间变量和日期的条件运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!