Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format column within dplyr chain

I have this data set:

dat <- 
structure(list(date = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L, 4L, 4L), .Label = c("3/31/2014", "4/1/2014", "4/2/2014", 
"4/3/2014"), class = "factor"), site = structure(c(1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("a", "b"), class = "factor"), 
clicks = c(73L, 64L, 80L, 58L, 58L, 61L, 70L, 60L, 84L, 65L, 
77L), impressions = c(55817L, 78027L, 77017L, 68797L, 92437L, 
94259L, 88418L, 55420L, 69866L, 86767L, 92088L)), .Names = c("date", 
"site", "clicks", "impressions"), class = "data.frame", row.names = c(NA, 
-11L))

dat
        date site clicks impressions
1  3/31/2014    a     73       55817
2  3/31/2014    b     64       78027
3  3/31/2014    a     80       77017
4   4/1/2014    b     58       68797
...

Is it possible include the date formatting of one column within the chain? (I've also tried using with, but that only returns the date column.)

library(dplyr)

> dat %.%
+   select(date, clicks, impressions) %.%
+   group_by(date) %.%
+   summarise(clicks = sum(clicks),
+             impressions = sum(impressions)) %.%
+   as.Date(Date, format = '%m/%d/%Y')
Error in as.Date.default(`__prev`, Date, format = "%m/%d/%Y") : 
  do not know how to convert '__prev' to class “Date”

If I don't include the formatting within the chain, it works. I know it's simple to write this outside of the chain, but I would like to confirm if this is doable.

dat %.%
select(date, clicks, impressions) %.%
group_by(date) %.%
summarise(clicks = sum(clicks),
          impressions = sum(impressions))

dat$date <- as.Date(dat$Date, format = '%m/%d/%Y')
like image 267
maloneypatr Avatar asked Apr 03 '14 18:04

maloneypatr


2 Answers

Is this what you want?

dat %>%
  select(date, clicks, impressions) %>%
  group_by(date) %>%
  summarise(clicks = sum(clicks),
            impressions = sum(impressions)) %>%
  mutate(date = as.Date(date, format = '%m/%d/%Y'))
like image 120
Robert Krzyzanowski Avatar answered Nov 04 '22 10:11

Robert Krzyzanowski


Sometimes the Error: cannot modify grouping variable message comes when you're trying to run group_by() operations on something that has already been grouped. You might try including ungroup first. In the syntax of Robert's answer:

dat %>%
  ungroup %>% 
  select(date, clicks, impressions) %>%
  group_by(date) %>%
  summarize(clicks      = sum(clicks),
            impressions = sum(impressions)) %>%
  mutate(date = as.Date(date, format = "%m/%d/%Y"))
like image 5
Pat W. Avatar answered Nov 04 '22 09:11

Pat W.