Reputation: 1004
I want to write a function that will accept a vector of columns that are of class character, that will convert them to date, and output the dataframe. When I run it, it outputs a list of dataframes but without the conversion taking place. Can I rewrite the below to achieve this? The context is that I might have lots of character columns that I want to convert and having a function seems the best way to achieve this.
library(tidyverse)
date1<-c("2021-01-05","2021-01-06","2021-01-07","2021-01-08","2021-01-09")
date2<-c("2021-02-05","2021-02-06","2021-02-07","2021-02-08","2021-02-09")
df<-data.frame(date1,date2,stringsAsFactors = FALSE)
#the vector of columns to convert to date format
datecols<-c("date1","date2")
datefunc<-function(a){
df2<-df%>%
mutate(a=as.Date(a,"%Y-%m-%d" ))
return(df2)}
df<-lapply(datecols,datefunc)
Upvotes: 2
Views: 224
Reputation: 21908
You can also use this.
library(dplyr)
library(lubridate)
datefunc <- function(a){
df2 <- df %>%
mutate(across(all_of(a), ~ ymd(.x)))
return(df2)
}
datefunc(datecols)
# A tibble: 5 x 2
date1 date2
<date> <date>
1 2021-01-05 2021-02-05
2 2021-01-06 2021-02-06
3 2021-01-07 2021-02-07
4 2021-01-08 2021-02-08
5 2021-01-09 2021-02-09
Upvotes: 2
Reputation: 388817
You don't need to specify format if the date has pattern 'Y-%m-%d'
. You can write a simple function which changes a single column to date and use lapply
to apply it for datecols
.
datefunc<-function(a) as.Date(a)
datecols<-c("date1","date2")
df[datecols] <- lapply(df[datecols], datefunc)
df
# date1 date2
#1 2021-01-05 2021-02-05
#2 2021-01-06 2021-02-06
#3 2021-01-07 2021-02-07
#4 2021-01-08 2021-02-08
#5 2021-01-09 2021-02-09
str(df)
#'data.frame': 5 obs. of 2 variables:
# $ date1: Date, format: "2021-01-05" "2021-01-06" "2021-01-07" ...
# $ date2: Date, format: "2021-02-05" "2021-02-06" "2021-02-07" ...
Upvotes: 2
Reputation: 101064
You can try
> list2DF(Map(as.Date, df))
date1 date2
1 2021-01-05 2021-02-05
2 2021-01-06 2021-02-06
3 2021-01-07 2021-02-07
4 2021-01-08 2021-02-08
5 2021-01-09 2021-02-09
Upvotes: 0
Reputation: 26218
df %>% mutate(across(everything(), ~as.Date(., format = "%Y-%m-%d")))
date1 date2
1 2021-01-05 2021-02-05
2 2021-01-06 2021-02-06
3 2021-01-07 2021-02-07
4 2021-01-08 2021-02-08
5 2021-01-09 2021-02-09
Upvotes: 0
Reputation: 65
Could this be helpful?
as.Date(df$date1, df$date2, format = "%Y/%m/%d/")
Upvotes: 1