I'm trying to change several variables within a data frame that are currently characters into time. I've imported only the variables I want from a csv file using
ids_dates_times <- read.csv("filename", header=TRUE, na.strings=c(".",NA),
stringsAsFactor = FALSE,
colClasses="character")[,c(1,3,8,9,10,15,16,17,22,23,24,29,30,31,36,37,38,43,44,45,50,51)]
Example of ids_dates_times (this is just first 4 variables, note there are 14 that need converted to times):
id_phresh D1_Date D1_Bed_Time D1_Wake_Time
1 1097 9/3/2016 15:16:00 8:59:00
2 1098 7/22/2016 2:00:00 6:30:00
3 2005 8/25/2016 23:00:00 6:00:00
4 2007 7/9/2016 1:00:00 7:00:00
5 2013 6/23/2016 23:45:00 8:35:00
I'd like my next line of code to convert selected columns to times.
times <- chron(times.= ids_dates_times[,c(3,4,6,7,9,10,12,13,15,16,18,19,21,22)], format = "hh:mm:ss")
I receive the following error
Error in convert.times(times., fmt) : format hh:mm:ss may be incorrect
I've tried the following:
itimes <- which(sapply(DF, function(x) all(grepl(":.*:", x))))
DF[itimes] <- lapply(DF[itimes], times)
idates <- which(sapply(DF, function(x) all(grepl("/.*/", x))))
DF[idates] <- lapply(DF[idates], dates)
which results in:
str(lapply(DF, class))
List of 22
$ id_phresh : chr "character"
$ D1_Date : chr "character"
$ D1_Bed_Time : chr "character"
$ D1_Wake_Time: chr "character"
These should should as date and time, not character, right? Any help would be awesome!