0

at the moment I'm trying to convert a string into time-format. e.g. my string looks like following: time <- '12:00'. I already tried to use the chron-Package. And my code looks like following:

time <- paste(time,':00', sep = '') time <- times(time)

Instead of getting a value like "12:00:00" the function times() always translate the object time into "0.5" Am I using the wrong approach?

regards

Leon
  • 371
  • 4
  • 11

1 Answers1

1

Your code works. If you check the 'class()' it is "times". However, if you want another way, try:

time <- '12:00:00'
newtime<-as.POSIXlt(time, format = "%H:%M:%S") # The whole date with time
t <- strftime(newtime, format="%H:%M:%S") # To extract the time part
t
#[1] "12:00:00"

Cheers !

Carles
  • 2,731
  • 14
  • 25
  • No it din't work. So the hole story - I'm getting the time object from an html import but before I used the times() function I converted the object with as.character(time) and in dataframe the object is shown as "12:00" – Leon Jun 13 '18 at 17:02
  • What is the `class(time)` before doing `as.characther(time)` ? – Carles Jun 13 '18 at 17:04
  • It's listed as factor - but in the data.frame is shown as normal string.. – Leon Jun 13 '18 at 17:26
  • I have two ideas: (1) try to write when you read the html if it is possible `stringsAsFactors = FALSE`. (2) Else, the problem might be that you are trying to do `as.character` to the whole data.frame . Try it by columns. Tell me if the problem gets solved. Cheers ! – Carles Jun 13 '18 at 17:40
  • To your second idea, I used this code segment: for (i in 1:nrow(table)) { table$time[i] <- as.character(table$time[i]) if(!is.na(table$time[i])){ table$time[i] <- times(table$time[i]) } } But this didn't worked – Leon Jun 13 '18 at 17:55
  • Can you provide with the document and how you read it ?, because I am confused. To me it works. – Carles Jun 13 '18 at 18:40