francoiskroll
francoiskroll

Reputation: 1108

R lubridate: Apply helper to dataframe

I have a dataframe of times looking like this:

library(lubridate)

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"), 
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")), 
                        row.names = c(NA, 3L), class = "data.frame")

I want to convert the times in more convenient date-time objects, which I will do with the hms() helper function from the lubridate package.

Running hms() on one column of my dataframe works like a charm:

hms(times[,1])

[1] "17H 19M 4S" "17H 28M 53S" "17H 38M 44S"

Great, surely I can just apply() on my whole dataframe then.

apply(times, 2, hms)

Which gives a weird dataframe with some integers, definitely not what I am expecting.

What is the right way to convert all of my times dataframe with the hms() function?

Upvotes: 0

Views: 74

Answers (2)

akrun
akrun

Reputation: 887651

Instead of apply, can use lapply as apply converts to matrix and it wouln't hold the attributes created by hms

library(lubridate)
times[] <- lapply(times, hms)
str(times)
#'data.frame':  3 obs. of  2 variables:
# $ exp1:Formal class 'Period' [package "lubridate"] with 6 slots
#  .. ..@ .Data : num  4 53 44
#  .. ..@ year  : num  0 0 0
#  .. ..@ month : num  0 0 0
#  .. ..@ day   : num  0 0 0
#  .. ..@ hour  : num  17 17 17
#  .. ..@ minute: num  19 28 38
# $ exp2:Formal class 'Period' [package "lubridate"] with 6 slots
#  .. ..@ .Data : num  4 53 45
#  .. ..@ year  : num  0 0 0
#  .. ..@ month : num  0 0 0
#  .. ..@ day   : num  0 0 0
#  .. ..@ hour  : num  17 17 17
#  .. ..@ minute: num  22 31 41

With the devel version of dplyr, we can use mutate with across

library(dplyr)
times %>%
    mutate(across(everything(), hms))

Upvotes: 2

d.b
d.b

Reputation: 32548

library(dplyr)
library(lubridate)

times %>% mutate_all(hms)
#OR
mutate_all(times, hms)
#         exp1        exp2
#1  17H 19M 4S  17H 22M 4S
#2 17H 28M 53S 17H 31M 53S
#3 17H 38M 44S 17H 41M 45S

Upvotes: 2

Related Questions