GJW
GJW

Reputation: 7

R: change multiple select columns in a dataframe data type to date format

I am looking to change multiple specific columns data type to POSIXct format in a dataframe. I have been able to do this individually - see below.

Is their a function to repeat this with just listing the columns of interest as opposed to repeating the lines of code ? When I have tried lubridate and POSIXct it limits me to naming a single column at a time.

Thank you for any pointers / direction. Much appreciated


study_ID <- c(5,6,7)
randomisation <- (c("2021-01-01 11:00", "2021-01-02 10:00", "2021-01-03 10:00"))
water_on <- (c("2021-01-01 13:00", "2021-01-02 09:00","2021-01-04 09:45"))
water_off <- (c("2021-01-01 18:00", "2021-01-02 18:00","2021-01-04 11:00"))
trial_A <- data.frame(study_ID, randomisation, water_on, water_off)
View(trial_A)

trial_A$randomisation <-as.POSIXct(trial_A$randomisation, format= "%Y-%m-%d %H:%M:%S")
tibble(trial_A)

trial_A_1 <- trial_A %>% mutate(water_on = ymd_hm(water_on))
tibble(trial_A_1)

Upvotes: 1

Views: 607

Answers (1)

Cettt
Cettt

Reputation: 11981

you can use the dplyr package to change multiple columns at the same time.

In your case you would use something like

library(dplyr)

trial_A_1 >%>
  mutate(across(c(randomization, water_on, water_off), ymd_hm))

across has two components. The first component specifies the relevant columns. The second component contains the function you want to apply.

For both components there are various shortcuts you can take. More details can be found in the help page.

Upvotes: 1

Related Questions