Home > Net >  How to make a function(x) accept x as a column name?
How to make a function(x) accept x as a column name?

Time:11-12

I have the following setup:

mydata:

  today_date
r1  11.11.21
r2  11.11.21
r3  11.11.21

I want to convert column like 'today_date' to a date using

as.Date(today_date,tryFormats = c("%d.%m.%Y")).

So I'm using the following function, which is supposed to change the corresponding column to proper dates:

myfun <- function(x){
  x<- as.Date(x,  tryFormats = c("%d.%m.%Y"))
}

In this function x is representing a variable corresponding to: mydata$today_date Sadly, x is properly representing the object that's to be replaced, so instead of:

myfun(mydata$today_date)

I still have to use:

mydata$today_date<- myfun(mydata$today_date)

How can I manipulate the function so the as.Date()-functionality is directly applied? I'm pretty certain that the variable in myfun(x) is not properly able to represent the subsection of my dataframe that I want to change. Any help is very welcome!

CodePudding user response:

Try doing this.

df <- data.frame(today_date = c("11.11.21","11.11.21","11.11.21"))

myfun <- function(df, var = 'today_date'){
  df[[var]] <- as.Date(df[[var]],  tryFormats = c("%d.%m.%Y"))
  return(df)
}

The output is

> myfun(df, "today_date")
  today_date
1 0021-11-11
2 0021-11-11
3 0021-11-11

CodePudding user response:

I like the magrittr assignment pipe syntax for this.

library(magrittr)
mydata$today_date %<>% myfun()

Instead of mydata$today_date<- myfun(mydata$today_date)

  • Related