1

Hey all I apologise if this is very simple and mediocre but I can't seem to create a function that turns a time variable (00:00:00) into a numeric AND creates a new column to put the result in.

I can turn the time into a numeric, I just cannot complete the 'new column' part. Any help is appreciated.

Time <- function(x) {
   begin <- x$avg..wait.time
  x$Num.wait.time <- as.numeric(as.POSIXct(strptime(begin, "%H:%M:%S")))
}

(NOTE: avg..wait.time is the time cell and Num.wait.time is the new variable/column I want to create)

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Jack
  • 15
  • 3
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Ronak Shah Jul 27 '18 at 01:10
  • I wouldn't make a function that adds a column - make the function just do your conversion on a vector and then add the column outside of the function like `df$newvar <- Time(df$avg.wait.time)` where `Time` is `Time <- function(x) as.numeric(as.POSIXct(x, format="%H:%M:%S"))` – thelatemail Jul 27 '18 at 03:12

1 Answers1

1

If your purpose is not in writing the function per se, with dplyr you can directly tackle the problem with existing wheels, and not have to write a separate function.

library(dplyr)
df <- data.frame(avg.wait.time = c("01:02:03", "03:02:01"))
df <- df %>% 
  dplyr::mutate(
    avg.wait.numeric = as.numeric(as.POSIXct(strptime(avg.wait.time, "%H:%M:%S")))
  )

If you wish to write a separate function, I would do as follows:

Time <- function(x, 
                 input_var = "avg.wait.time", 
                 output_var = "avg.wait.numeric") {
  x[[output_var]] <- 
    as.numeric(as.POSIXct(strptime(x[[input_var]], "%H:%M:%S")))
  return(x)
}

This allows the input variable name and output variable name to be specified, currently set with some arbitrary default values (you can kick these out, of course).

Kim
  • 4,080
  • 2
  • 30
  • 51
  • This works a charm thank you, It returns the appropriate value. Although, I can't call on `avg.wait.numeric` after I run the function. Is there a simple way I can run the function, and still have the column to call on afterwards? – Jack Jul 27 '18 at 01:48
  • @Jack Uhh, could you clarify a little bit? Perhaps you mean that simply running `Time(df)` will show a wrangled dataframe but not stored in the global environment. You would need to do `df <- Time(df)` if you wish to overwrite the existing dataframe? – Kim Jul 27 '18 at 01:53
  • Sorry for my lack of communication, this is my first time asking a question on Stack Overflow. That is what I meant to say, thank you. Problem solved! – Jack Jul 27 '18 at 01:57
  • @Jack Magnificent! Feel free to accept the answer if you found it useful. – Kim Jul 27 '18 at 01:58