将文本转换为R中的特定日期格式

时间:2015-10-06 18:52:43

标签: r date strptime

我有以下字符(样本):

>trial
[1] "9-5"  "7-5"  "13-3" "17-6"

我想将它们转换为日期格式(如果可能),并变为类似以下内容:

>trial
[1] Friday 9:00  Friday 7:00  Wednesday 13:00  Saturday 17:00

我正在使用以下代码,这不是理想的结果:

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

我的观点是我希望工作日和小时的日期格式。怎么办呢?

2 个答案:

答案 0 :(得分:2)

以下是我可能会做的事情:

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"

+ 1是必需的,因为wday函数将星期日视为第1天; OP使用星期一。

评论。可以更简洁地编写(仅调用trial一次)

setDT(tstrsplit(trial, "-", type.convert=TRUE))[, 
  paste0(wdays[V2 + 1], " ", V1, ":00")
]

您可以通过查看中间结果来了解其工作原理:

data.table(trial)[,tstrsplit(trial, "-", type.convert=TRUE)]
#    V1 V2
# 1:  9  5
# 2:  7  5
# 3: 13  3
# 4: 17  6

答案 1 :(得分:1)

尝试:

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"

或者为了解释发生了什么,我将在中间步骤中展示它:

#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"