0

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!

2 Answers2

5

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"))
An economist
  • 1,301
  • 1
  • 15
  • 35
  • That worked, thanks! You're right in that the piping operator isn't any better for this example. The project I'm working on though, I'm using more than just the as.Date in the pipe. –  Jun 30 '17 at 16:09
1

In this case you want to use the %$% operator that gives you access to columns directly:

df %$% as.Date(dates, "%m/%d/%Y")
# [1] "2017-04-13" "2017-02-20" "2017-03-05" "2017-04-14" "2017-10-22"

It's similar to the following syntax using with :

with(df,as.Date(dates, "%m/%d/%Y"))
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167