0

So I wrote a simple function which converts to the 'Date' datatype.

f_change_date <- function(column) {
  column <- as.Date(column)
}
f_change_date(df$Date.of.Launch)

Nothing happens. I also tried this:

f_change_date <- function(df, column) {
  column <- df %>% transmute(column = as.Date(column))
}
f_change_date(df, df$Date.of.Launch)

Nothing happens here too. But if I do the the as.Date operation outside of the function, then it works completely fine. For example:

df$Date.of.Launch <- as.Date(df$Date.of.Launch)

This works and change the datatype of df$Date.of.Launch. Am I writing functions wrongly?

purple1437
  • 313
  • 1
  • 8
  • I think this discussion will be helpful - [Update data frame via function doesn't work](https://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work) – thelatemail May 28 '21 at 00:35

1 Answers1

0

We can use

library(dplyr)
f_change_date <- function(df, column) {
     df %>% 
             transmute({{column}} := as.Date({{column}}))
   }

df <- f_change_date(df, Date.of.Launch)

-checking

str(df)
#'data.frame':  2 obs. of  1 variable:
# $ Date.of.Launch: Date, format: "2015-05-09" "2020-06-10"

data

df <- data.frame(Date.of.Launch = c('2015-05-09', '2020-06-10'))

 
akrun
  • 874,273
  • 37
  • 540
  • 662