I have df1:
ID Time
1 16:00:00
2 14:30:00
3 9:23:00
4 10:00:00
5 23:59:00
and would like to change the current 'character' column 'Time' into a an 'integer' as below:
ID Time
1 1600
2 1430
3 923
4 1000
5 2359
CodePudding user response:
We could replace the :
's, make numeric, divide by 100, and convert to integer like this:
df1$Time = as.integer(as.numeric(gsub(':', '', df1$Time))/100)
CodePudding user response:
You want to use as.POSIXct()
.
Functions to manipulate objects of classes "POSIXlt" and "POSIXct" representing calendar dates and times.
So in the case of row 1: as.POSIXct("16:00:00", format = "%H%M")
Then use as.numeric
if you need it to truly be an int.
Converts a character matrix to a numeric matrix.
CodePudding user response:
df1 <- data.frame(Time = "16:00:00")
df1[, "Time"] <- as.numeric(paste0(substr(df1[, "Time"], 1, 2), substr(df1[, "Time"], 4, 5)))
print(df1)
# Time
# 1 1600
CodePudding user response:
There are many ways to process this, but here's one example:
library(dplyr)
df1 <- mutate(df1, Time = gsub(":", "", Time) # replace colons with blanks
df1 <- mutate(df1, Time = as.numeric(Time)/100) # coerce to numeric type, divide by 100