Jake
Jake

Reputation: 285

Using `mutate_at()` with `as.Date()`

I'm trying to use mutate_at() from dplyr to coerce date-like columns into columns of type Date using as.Date(), but I'm getting an error. Here's the code:

library(dplyr)

df = data.frame(date_1 = "7/5/2014", date_2 = "7/22/2011")
df %>%
    mutate_at(.vars = c("date_1", "date_2"), .funs = as.Date("%m/%d/%Y"))

This gives me an error: Error in charToDate(x): character string is not in a standard unambiguous format

Not sure what's going on here, so I'd appreciate your help. I prefer dplyr solutions, but if there's a better way to do it, I'm open to that as well.

Upvotes: 2

Views: 5329

Answers (1)

zacdav
zacdav

Reputation: 4671

I personally prefer using the syntax as so: The . here refers to the column, which needs to be passed to the as.Date function.

library(dplyr)
df = data.frame(date_1 = "7/5/2014", date_2 = "7/22/2011")
df %>%
  mutate_at(vars(date_1, date_2), funs(as.Date(., "%m/%d/%Y")))

Upvotes: 6

Related Questions