简体   繁体   English

在 R 中分离关于月、日、年和小时的数据

[英]separating data with respect to month, day, year and hour in R

I have two columns in a data frame first is water consumption and the second column is for date+hour.我在数据框中有两列,第一列是耗水量,第二列是日期+小时。 for example Value Time 12.2 1/1/2016 1:00 11.2 1/1/2016 2:00 10.2 1/1/2016 3:00例如价值时间 12.2 1/1/2016 1:00 11.2 1/1/2016 2:00 10.2 1/1/2016 3:00

The data is for 4 years and I want to create separate columns for month date year and hour.数据是 4 年,我想为月份日期年份和小时创建单独的列。

I would appreciate any help我将不胜感激任何帮助

We can convert to Datetime and then extract the components.我们可以转换为Datetime ,然后提取组件。 We assume the format of 'Time' column is 'dd/mm/yyyy H:M' (in case it is different ie 'mm/dd/yyyy H:M', change the dmy_hm to mdy_hm )我们假设 'Time' 列的格式是 'dd/mm/yyyy H:M'(如果它不同,即 'mm/dd/yyyy H:M',请将dmy_hm更改为mdy_hm

library(dplyr)
library(lubridate)
df1 %>% 
  mutate(Time = dmy_hm(Time), month = month(Time), 
   year = year(Time), hour = hour(Time))
#  Value                Time month year hour
#1  12.2 2016-01-01 01:00:00     1 2016    1
#2  11.2 2016-01-01 02:00:00     1 2016    2
#3  10.2 2016-01-01 03:00:00     1 2016    3

In base R , we can either use strptime or as.POSIXct and then use either format or extract componentsbase R ,我们可以使用strptimeas.POSIXct然后使用format或提取组件

df1$Time <- strptime(df1$Time, "%d/%m/%Y %H:%M")
transform(df1, month = Time$mon+1, year = Time$year + 1900, hour = Time$hour)
#  Value                Time month year hour
#1  12.2 2016-01-01 01:00:00     1 2016    1
#2  11.2 2016-01-01 02:00:00     1 2016    2
#3  10.2 2016-01-01 03:00:00     1 2016    3

data数据

df1 <- structure(list(Value = c(12.2, 11.2, 10.2), Time = c("1/1/2016 1:00", 
"1/1/2016 2:00", "1/1/2016 3:00")), class = "data.frame", row.names = c(NA, 
-3L))

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

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