我是R的新手,我正在寻找一种方法来提取我的数据帧中的小时分钟和借调。我尝试了一些库,但没有成功。
这是我目前的代码:
daily_data = read.csv("/Us/eco.csv", header=TRUE, stringsAsFactors=FALSE)
daily_hour= daily_data$time
daily_hour
以下是我约会的日期:
[1] "2016-08-19 17:45:19" "2016-08-19 17:45:19" "2016-08-19 17:45:19" "2016-08-19 17:45:19"
[5] "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19"
[9] "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19"
[13] "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 19:27:07"
[17] "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 23:33:46" "2016-08-19 23:33:46"
[21] "2016-08-19 23:33:46" "2016-08-19 23:33:46" "2016-08-20 07:13:32" "2016-08-20 07:13:32"
[25] "2016-08-20 07:13:32" "2016-08-20 07:13:32" "2016-08-20 08:52:12" "2016-08-20 08:52:12"
[29] "2016-08-20 08:52:12" "2016-08-20 08:52:12" "2016-08-20 10:06:53" "2016-08-20 10:06:53"
[33] "2016-08-20 10:06:53" "2016-08-20 10:06:53" "2016-08-20 10:06:56" "2016-08-20 10:06:56"
答案 0 :(得分:1)
hms <- sub('\\d+-\\d+-\\d+ ', '', daily_hour)
会将字符串的小时:分钟:秒部分提取为字符串。如果您需要将这些变量分成其他变量,则有两种选择。
# Option 1
hours <- sub(':\\d+:\\d+', '', hms)
mins <- sub('\\d+:(\\d+):\\d+', '\\1', hms)
secs <- sub('\\d+:\\d+:', '', hms)
# Option 2
daily_hour <- as.POSIXct(daily_hour)
hours <- as.numeric(format(daily_hour, "%H"))
mins <- as.numeric(format(daily_hour, "%M"))
secs <- as.numeric(format(daily_hour, "%S"))
答案 1 :(得分:0)
假设您的数据:
daily_hour = data.frame(time = c("2016-08-19 17:45:19", "2016-08-19 17:45:36"))
然后将其拆分为sep = " "
并获取列表的第二个元素,您将获得一个hh:mm:ss的向量:
sapply(daily_hour$time, function(x) strsplit(as.character(x), " ")[[1]][2])
答案 2 :(得分:0)
如果您的日期格式一致,您还可以使用substr
。
substr(daily_hour, 12, 19)
substr("2016-08-19 17:45:19", 12, 19)
[1] "17:45:19"