Reputation: 523
I have a column that I have already changed to DATE using as.date
> test_subset$Date <- as.Date(test_subset$Date, "%d/%m/%Y")
The next column holds numeric data as the times corresponding to adjacent column of dates. The problem I have is it keeps inserting the current date into this time only column - I specify column "TIME"
> test_subset[[2]] <- strptime(test_subset[[2]], "%H:%M:%S")
but the result appends the current date to the time.
Upvotes: 0
Views: 1940
Reputation: 99331
The date is being inserted because you're using strptime()
. You can use format()
, since you don't necessarily need a special class for the times. If we have an example vector x
,
x <- Sys.time() + 0:5
#[1] "2015-03-05 07:08:27 PST" "2015-03-05 07:08:28 PST"
#[3] "2015-03-05 07:08:29 PST" "2015-03-05 07:08:30 PST"
#[5] "2015-03-05 07:08:31 PST" "2015-03-05 07:08:32 PST"
To get the date only, you can use
as.Date(format(x, "%F"))
# [1] "2015-03-05" "2015-03-05" "2015-03-05" "2015-03-05"
# [5] "2015-03-05" "2015-03-05"
And to get the time only, use format()
again, but with %T
.
format(x, "%T")
# [1] "07:08:27" "07:08:28" "07:08:29" "07:08:30" "07:08:31"
# [6] "07:08:32"
If it turns out you do need a time class on the second column, you can use chron::times()
which gives a "times" class.
(time <- chron::times(format(x, "%T")))
# [1] 07:08:27 07:08:28 07:08:29 07:08:30 07:08:31 07:08:32
class(time)
# [1] "times"
Upvotes: 1