Reputation: 3450
Originally I have this code which I am trying to simplify and improve readability using %>% operator.
#Get Sunday's from 2018-01-01 till today
d = seq(as.Date("2018-01-01"),Sys.Date()+365,by='day')
HolidayList = data.frame(Holidays=d[weekdays(d)=='Sunday'])
#Get Alternate saturdays 2nd and 4th
d = seq(as.Date("2018-01-01"),Sys.Date()+365,by='day')
saturdayList = d[weekdays(d)=='Saturday']
altSaturdayList = lapply(split(saturdayList, format(saturdayList, "%Y-%m")), function(x)
na.omit(x[c(2,4)]))
altSaturdayList = as.data.frame(altSaturdayList)
altSaturdayList = gather(altSaturdayList)
altSaturdayList = subset(altSaturdayList,select = c(value))
HolidayList = rbind(HolidayList, setNames(altSaturdayList, "Holidays"))
HolidayList = rbind(HolidayList, setNames(as.data.frame(as.Date("2018-11-06")), "Holidays"))
HolidayList = unique(HolidayList)
HolidayList = arrange(HolidayList,Holidays)
rm(d)
rm(saturdayList)
rm(altSaturdayList)
I don't want to store the intermediate variables that's why I thought pipe operator would be a good choice but I am not able to reproduce the result.
Here's what I tried
HolidayList = saturdayList %>%
data.frame(lapply(split(saturdayList, format(saturdayList, "%Y-%m")), function(x)
na.omit(x[c(2,4)]))) %>%
subset(gather(altSaturdayList),select = c(value)) %>%
rbind(HolidayList, setNames(altSaturdayList, "Holidays")) %>%
rbind(HolidayList, setNames(as.data.frame(as.Date("2018-11-06")), "Holidays")) %>%
arrange(unique(HolidayList),Holidays)
Holidays
dataframe has dates to which I am trying to bind and add new dates.
How do I take output of each step and put as input in next line without creating new variables?
Please explain the steps so that I can understand the process to simplify above code.
Upvotes: 0
Views: 323
Reputation: 388862
There are functions which are specially designed for pipe operators in tidyverse
. Those functions are well suited for using pipe operators instead of using base R operators and trying to fit them in pipe. You can still use base R functions in pipe but it is more convenient to use them using tidyverse
tools.
library(tidyverse)
temp <- map_dfr(split(saturdayList,format(saturdayList, "%Y-%m")), ~ .[c(2, 4)]) %>%
gather(key, Holidays) %>%
select(Holidays) %>%
bind_rows(HolidayList) %>%
add_row(Holidays = as.Date("2018-11-06")) %>%
unique() %>%
na.omit() %>%
arrange(Holidays)
temp
# Holidays
# <date>
# 1 2018-01-07
# 2 2018-01-13
# 3 2018-01-14
# 4 2018-01-21
# 5 2018-01-27
# 6 2018-01-28
# 7 2018-02-04
# 8 2018-02-10
# 9 2018-02-11
#10 2018-02-18
# … with 160 more rows
To confirm if output from both of them is the same we can convert temp
to data frame and then compare to HolidayList
in your final step.
identical(data.frame(temp), HolidayList)
#[1] TRUE
Upvotes: 2