Home > OS >  Merging two lines of code into one using indexing or any other tool
Merging two lines of code into one using indexing or any other tool

Time:04-03

I have two differnet lines of code which performing same thing but for two different columns. I tried different methods to merge them into just one line of code but everytime I get an error.

Code is just to tranform datetime column from chr to dttm:

df[["started_at"]] <- as.POSIXct(df[["started_at"]], format = "%Y-%m-%d %H:%M:%S") %>% ymd_hms()
df[["ended_at"]] <- as.POSIXct(df[["ended_at"]], format = "%Y-%m-%d %H:%M:%S") %>% ymd_hms()

CodePudding user response:

If you are comfortable with the package dplyr, you can use mutate() with across().

Input

I've created a dummy dataframe df for demonstration.

library(dplyr)
library(lubridate)

# dummy dataframe
df <- tibble(started_at = "2020-01-30 11:11:11", 
             ended_at = "2020-12-06 15:43:26", 
             ID = "123")

# A tibble: 1 × 3
  started_at          ended_at            ID   
  <chr>               <chr>               <chr>
1 2020-01-30 11:11:11 2020-12-06 15:43:26 123  

Solution

df <- df %>% mutate(across(c(started_at, ended_at), 
                           ~ as.POSIXct(.x, format = "%Y-%m-%d %H:%M:%S") %>% 
                             ymd_hms()))

# A tibble: 1 × 3
  started_at          ended_at            ID   
  <dttm>              <dttm>              <chr>
1 2020-01-30 11:11:11 2020-12-06 15:43:26 123  

CodePudding user response:

Any of

df %>% mutate(across(c(started_at, ended_at), as.POSIXct))
df %>% mutate(across(c(started_at, ended_at), ymd_hms))

will coerce to class "POSIXct".
If you know that the date/time columns are the only ones ending in "_at" , you can simplify the code above to any of

df %>% mutate(across(ends_with("_at"), as.POSIXct))
df %>% mutate(across(ends_with("_at"), ymd_hms))

On both case, the rule is

  • If you want to avoid loading another package, lubridate, just for this, use the code line calling as.POSIXct.
  • If you need more date and time functions, to load and use package lubridate is probably a good idea.
  • Related