Home > Enterprise >  R iterate over a dictionary into a function for multiple values
R iterate over a dictionary into a function for multiple values

Time:11-23

I am trying to create a loop (or the most efficient way) to iterate over a series of calendars in R (or Python!) to post ALL holidays (ideally it would be all business days, but it seems like I might design two parts to this - as I would like weekends flagged). The goal is to have a dataframe that looks like:

Country | ISO Code (if available) | Dates
United States of America| US| 12.24.2020
United States of America| US| 12.25.2020
United States of America| US| 01.01.2021
United Kingdom| UK| 12.24.2020
United Kingdom| UK| 12.25.2020
United Kingdom| UK| 01.01.2021

What I have so far:

    require("lattice")
    require("reticulate")
    require("RcppQuantuccia")
    require("tidyverse")
    require("tidytable")

fun_Holidays <- function(cal) {
    setCalendar(cal)
    getHolidays(as.Date("2019-01-01"), as.Date("2030-12-31"))
}
cal_dic <- data.table(calendar=calendars)
as.list(cal_dic)

cal_dic is the list of all of the calendars available on RcppQuantuccia but if I run:

fun_Holidays(cal_dic)

All I get is the error (because it is not iterative):

ERROR: Error in setCalendar(cal): Expecting a single string value: [type=list; extent=1].

I have also taken a stab at this in Python using the Holidays package and got further along but the ISO code doesn't append correctly:

all_holidays = []
country_list = ['Angola','Argentina','Aruba','Australia','Austria','Bangladesh','Belarus','Belgium','Botswana','Brazil',
                'Bulgaria','Burundi','Canada','Chile','China','Colombia','Croatia','Curacao','Czechia','Denmark','Djibouti','DominicanRepublic',
                'Egypt','England','Estonia','Finland','France','Georgia','Germany','Greece','Honduras','HongKong','Hungary','Iceland','India','Ireland','IsleOfMan',
                'Israel','Italy','Jamaica','Japan','Kenya','Korea','Latvia','Lesotho','Lithuania','Luxembourg','Malaysia','Malawi','Mexico','Morocco','Mozambique','Netherlands',
                'Namibia','NewZealand','Nicaragua','Nigeria','NorthernIreland','Norway','Paraguay','Peru','Poland','Portugal','PortugalExt','Romania','Russia','SaudiArabia','Scotland',
                'Serbia','Singapore','Slovakia','Slovenia','SouthAfrica','Spain','Swaziland','Sweden','Switzerland','Turkey','Ukraine','UnitedArabEmirates','UnitedKingdom',
                'UnitedStates','Venezuela','Vietnam','Wales','Zambia','Zimbabwe']
    

for country in country_list:
    for holiday in holidays.CountryHoliday(country, years = np.arange(2018,2030,1)).items():
        all_holidays.append({'date' : holiday[0], 'holiday' : holiday[1], 'country': country, 'code': code})
all_holidays = pd.DataFrame(all_holidays)
all_holidays

    date    holiday country code
0   2018-09-17  Dia do Herói Nacional   Angola  NZ
1   2018-01-01  Ano novo    Angola  NZ
2   2018-03-30  Sexta-feira Santa   Angola  NZ
3   2018-02-13  Carnaval    Angola  NZ
4   2018-02-04  Dia do Início da Luta Armada    Angola  NZ
... ... ... ... ...
14386   2029-08-15  Zimbabwe Heroes' Day    Zimbabwe    NZ
14387   2029-08-13  Defense Forces Day  Zimbabwe    NZ
14388   2029-12-22  Unity Day   Zimbabwe    NZ
14389   2029-12-25  Christmas Day   Zimbabwe    NZ
14390   2029-12-26  Boxing Day  Zimbabwe    NZ
14391 rows × 4 columns

I find it very odd that there isn't a master list of holidays by country by date in csv or such to help with time series - but maybe that's just me! :)

Thanks!

EDIT: I have also been looking at: https://workalendar.github.io/workalendar/

as this has the largest list of countries but it is much more difficult to work with than Holidays - but if someone has a solution to get the "master calendar" out of workaldendar that would be amazing!

CodePudding user response:

Use lapply to get list of dates for each value in calendars.

library(RcppQuantuccia)

fun_Holidays <- function(cal) {
  setCalendar(cal)
  getHolidays(as.Date("2019-01-01"), as.Date("2030-12-31"))
}


lapply(calendars, fun_Holidays)

To create a single dataframe with country name and dates you can use -

do.call(rbind, lapply(calendars, function(x) {
  dates <- fun_Holidays(x)
  if(length(dates))
    data.frame(country = x, dates)
})) -> result

head(result)

#  country      dates
#1  TARGET 2019-01-01
#2  TARGET 2019-04-19
#3  TARGET 2019-04-22
#4  TARGET 2019-05-01
#5  TARGET 2019-12-25
#6  TARGET 2019-12-26

Or with purrr -

purrr::map_df(calendars, function(x) {
  dates <- fun_Holidays(x)
  if(length(dates))
    data.frame(country = x, dates)
}) -> result
  • Related