Reputation: 4991
I have the following characters(sample):
>trial
[1] "9-5" "7-5" "13-3" "17-6"
And I want to convert them to date format(if possible) and become something like the following:
>trial
[1] Friday 9:00 Friday 7:00 Wednesday 13:00 Saturday 17:00
I am using the following code, which is not the desired result:
>strptime(trial,format="%k-%w")
[1] "2015-10-06 09:00:00 CEST" "2015-10-06 07:00:00 CEST"
[3] "2015-10-06 13:00:00 CEST" "2015-10-06 17:00:00 CEST"
My point is that I want to have date format for weekdays and hour. How can it be done?
Upvotes: 0
Views: 115
Reputation: 28441
Try:
paste(weekdays((as.Date("1970-01-01")+4)+0:7)[as.numeric(sub(".*-(\\d+)", "\\1", trial))], sub("(\\d+).*", "\\1:00", trial))
[1] "Friday 9:00" "Friday 7:00" "Wednesday 13:00"
[4] "Saturday 17:00"
Or to explain what is going on I'll show it in intermediate steps:
#1. starting vector
trial <- c("9-5", "7-5", "13-3", "17-6")
#2. get the hour and add ":00" to the values
hr <- sub("(\\d+).*", "\\1:00", trial)
#3. get the day of the week as a number
d <- as.numeric(sub(".*-(\\d+)", "\\1", trial))
#4. pick a week with a Monday date that you know and add 6 days (I use The first Monday after the origin). Subset with 'd'
day_vector <- weekdays((as.Date("1970-01-01")+4)+0:7)[d]
#5. paste day and hour together
paste(day_vector, hr)
[1] "Friday 9:00" "Friday 7:00" "Wednesday 13:00"
[4] "Saturday 17:00"
Upvotes: 1
Reputation: 66819
Here's what I might do:
library(data.table) # for wday & tstrsplit
a_wk <- Sys.Date()+1:7
wdays <- weekdays(a_wk)[ order(wday(a_wk)) ]
# "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"
data.table(trial)[,tstrsplit(trial, "-", type.convert=TRUE)][,
paste0(wdays[V2 + 1], " ", V1, ":00")
]
# "Friday 9:00" "Friday 7:00" "Wednesday 13:00" "Saturday 17:00"
The + 1
is needed because the wday
function takes Sunday as day 1; while the OP uses Monday.
Comments. It could be written more concisely (only invoking trial
once) as
setDT(tstrsplit(trial, "-", type.convert=TRUE))[,
paste0(wdays[V2 + 1], " ", V1, ":00")
]
You can see how this works by having a look at the intermediate result:
data.table(trial)[,tstrsplit(trial, "-", type.convert=TRUE)]
# V1 V2
# 1: 9 5
# 2: 7 5
# 3: 13 3
# 4: 17 6
Upvotes: 2