Reputation: 15
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)
Upvotes: 1
Views: 59
Reputation: 4288
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).
Upvotes: 1