Emrb
Emrb

Reputation: 75

Using magrittr to change a subset of values

I have a time series dataframe with a day of the week column. I would like to replace all of the Mondays (day 1) that are holidays with a 6 for Sunday without breaking my pipeline using magrittr.

Without pipelines it looks like this:

dates = c("5/24/15", "5/25/15", "5/26/15", "5/27/15", "5/28/15", "5/29/15", "5/30/15")
df <- data.frame(date = as.POSIXct(dates,format = "%m/%d/%y"), day = 0:6, value = 1:7)
holidays <- c("2015-05-25")
df$day[df$date %in% as.POSIXct(holidays)] <- 6

But I would like to do something like this:

df <- df %>%
  filter(value < 30) %>%
  mutate(new_variable = something) %>%
  REPLACE HOLIDAYS WITH SUNDAY HERE

Upvotes: 3

Views: 712

Answers (1)

Neal Fultz
Neal Fultz

Reputation: 9687

use %in% to make the index, then replace with mutate I guess:

df %>% mutate(day=replace(day, date %in% as.POSIXct(holidays), 6))

Upvotes: 2

Related Questions