Reputation: 5555
I have the following data
Num Date Time
1 2015.05.21 12:12:12
2 2015.05.22 13:12:12
3 2015.05.23 14:12:12
4 2015.05.24 15:12:12
5 2015.05.25 16:12:12
By using weekdays(as.Date(data$Date, format='%Y.%m.%d'))
I can get the corresponding days of the week. Also by using months
I can get the corresponding months. Is there a way to get the hour only in a new column? Something like hours(as.Date(data$Time, format='%H:%M:%S'))
which will provide me the following output.
Num Date Time Hour
1 2015.05.21 12:12:12 12
2 2015.05.22 13:12:12 13
3 2015.05.23 14:12:12 14
4 2015.05.24 15:12:12 15
5 2015.05.25 16:12:12 16
Upvotes: 2
Views: 307
Reputation: 206187
R doesn't have a native data type for just time values without dates. With the sample data
dd<-read.table(text="Num Date Time
1 2015.05.21 12:12:12
2 2015.05.22 13:12:12
3 2015.05.23 14:12:12
4 2015.05.24 15:12:12
5 2015.05.25 16:12:12", header=T, stringsAsFactors=F)
You can do
transform(dd, Hour=as.POSIXlt(paste(Date, Time), format="%Y.%m.%d %H:%M:%S")$hour)
to get
Num Date Time Hour
1 1 2015.05.21 12:12:12 12
2 2 2015.05.22 13:12:12 13
3 3 2015.05.23 14:12:12 14
4 4 2015.05.24 15:12:12 15
5 5 2015.05.25 16:12:12 16
Upvotes: 2