简体   繁体   English

在 R 中处理日期和时间数据

[英]processing date and time data in R

Dear all, I have a data frame which comes directly from a sensor.亲爱的,我有一个直接来自传感器的数据帧。 The data provide the date and time in a single column.数据在单列中提供日期和时间。 I want R to be able to recognise this data and then create an adjacent column in the data frame which gives a number that corresponds to a new day in the time and date column.我希望 R 能够识别这些数据,然后在数据框中创建一个相邻的列,该列给出一个与时间和日期列中的新日期相对应的数字。 For example 25/02/2011 13:34 in data$time.date would give 1 in the new column data$day, and 26/02/2011 13:34 in data$time.date would get 2 and so on....例如,data$time.date 中的 25/02/2011 13:34 将在新列 data$day 中给出 1,而 data$time.date 中的 26/02/2011 13:34 将得到 2,依此类推。 ..

Does anyone know how to go about solving this?有谁知道如何解决这个问题? Thanks in advance for any help.在此先感谢您的帮助。

You can use cut() and convert to numeric the factor resulting from that call .您可以使用cut() 并将该调用产生的因子转换为数字 Here is an example with dummy data:这是一个带有虚拟数据的示例:

> sdate <- as.POSIXlt("25/02/2011 13:34", format = "%d/%m/%Y %H:%M")
> edate <- as.POSIXlt("02/03/2011 13:34", format = "%d/%m/%Y %H:%M")
> df <- data.frame(dt = seq(from = sdate, to = edate, by = "hours"))
> head(df)
                   dt
1 2011-02-25 13:34:00
2 2011-02-25 14:34:00
3 2011-02-25 15:34:00
4 2011-02-25 16:34:00
5 2011-02-25 17:34:00
6 2011-02-25 18:34:00

We cut the date time column into days using cut() .我们使用cut()将日期时间列切成天。 This results in a factor with the dates as labels. 这会导致将日期作为标签的因素。 We convert this factor to numerics to get 1, 2, ... : 我们将此因子转换为数字以得到 1, 2, ...

> df <- within(df, day <- cut(dt, "day", labels = FALSE))
> head(df, 13)
                    dt day
1  2011-02-25 13:34:00   1
2  2011-02-25 14:34:00   1
3  2011-02-25 15:34:00   1
4  2011-02-25 16:34:00   1
5  2011-02-25 17:34:00   1
6  2011-02-25 18:34:00   1
7  2011-02-25 19:34:00   1
8  2011-02-25 20:34:00   1
9  2011-02-25 21:34:00   1
10 2011-02-25 22:34:00   1
11 2011-02-25 23:34:00   1
12 2011-02-26 00:34:00   2
13 2011-02-26 01:34:00   2

You can achieve this using cut.POSIXt.您可以使用 cut.POSIXt 来实现这一点。 For example:例如:

dat <- data.frame(datetimes = Sys.time() - seq(360000, 0, by=-3600))
dat$day <- cut(dat$datetimes, breaks="day", labels=FALSE)

Note that this assumes your date time column is correclty formated as a date-time class.请注意,这假设您的日期时间列正确格式化为日期时间类。

See ?DateTimeClasses for details.有关详细信息,请参阅?DateTimeClasses

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

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