简体   繁体   中英

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

The data is for 4 years and I want to create separate columns for month date year and hour.

I would appreciate any help

We can convert to Datetime and then extract the components. 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 )

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 components

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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