Search code examples
rpipingmagrittras.date

R Error trying to use as.Date in a %>%


I recently learned about the piping operator %>% and I'm trying to incorporate into some of the projects I've been working on. I receive an error though when I try to use as.Date in the pipe.

Example

numbers <- c(1, 2, 3, 4, 5)
dates <- c("4/13/2017", "2/20/2017", "3/5/2017", "4/14/2017", "10/22/2017")
df <- data.frame(numbers, dates)
  numbers      dates
1       1  4/13/2017
2       2  2/20/2017
3       3   3/5/2017
4       4  4/14/2017
5       5 10/22/2017

Normally what I'd use is:

df$dates <- as.Date(df$dates, "%m/%d/%Y")

When trying to use it in a pipe, I tried:

df %>%
  as.Date(dates, "%m/%d/%Y")

But receive an error message:

Error in as.Date.default(., dates, "%m/%d/%Y") : 
  do not know how to convert '.' to class “Date”

I'm still not super familiar with piping operators so it is very likely that as.Date wouldn't be a command you'd use in a pipe.

Thanks in advance for any thoughts or suggestions!


Solution

  • I think you have to add mutate to the piping operator. However, I don't know if in this case piping operator is any better than just simple df$dates <- as.Date(df$dates, "%m/%d/%Y")

    library(dplyr)
    
    numbers <- c(1, 2, 3, 4, 5)
    dates <- c("4/13/2017", "2/20/2017", "3/5/2017", "4/14/2017", "10/22/2017")
    df <- data.frame(numbers, dates)
    
    df %>%
      mutate(dates=as.Date(dates, "%m/%d/%Y"))