我有一个类似于dd
的数据框
dd = data.frame(date = as.Date(c("2014-04-29", "2014-04-29","2014-04-29", "2014-04-29", "2014-04-29", "2014-04-29"), format ="%Y-%m-%d"), hh = 1:6, mm = seq(0, 50, 10))
我想创建新变量,将其称为time1
和time2
,其中
time1
是一天中的时间,无论日期如何,例如:第1行time1 = 01:00
[hh:mm]没有条目进入time2
是date + time1
;例如第1行time2 = 2014-04-29 : 01:00
任何建议都表示赞赏!
答案 0 :(得分:1)
查看lubridate
包:
library(lubridate)
dd$time1 <- with(dd, hm(paste(hh, mm, sep=":")))
dd$time2 <- with(dd, ymd(dd$date) + time1)
答案 1 :(得分:0)
使用基础R
dd$time1 <- format(strptime(paste0(dd$hh, ":", dd$mm), "%H:%M"), "%H:%M")
dd$time2 <- format(strptime(paste0(dd$date, ":", dd$hh, ":", dd$mm), "%Y-%m-%d:%H:%M"), "%Y-%m-%d : %H:%M")
这将导致
dd$time1
## [1] "01:00" "02:10" "03:20" "04:30" "05:40" "06:50"
dd$time2
## [1] "2014-04-29 : 01:00" "2014-04-29 : 02:10" "2014-04-29 : 03:20" "2014-04-29 : 04:30"
##v[5] "2014-04-29 : 05:40" "2014-04-29 : 06:50"
虽然他们不会成为Date
类型(请参阅@MrFlick评论)