I am looking for a purrr solution to accomplish what I have done with a for loop. I suspect it will be a version of map2 or pmap. I've looked at the documentation and it makes sense for the simple cases provided, but I haven't been able to figure out how to use this for my case.
In the data frame below, the "Sum" columns contain monthly forecast for a given SKU. The "End of" columns contain the month-end date for the given month. The rule I am applying is that if the year (last two digits in the End of columns) is greater than 22, I replace the corresponding values in the Sum column for the given month/SKU with 0. The code I currently use (which works) is below.
sample.data.frame <- data.frame(SKU = c('ABC', 'DEF', 'GHI'),
'Sum Month 01' = c(3, 9, 8), 'Sum Month 02' = c(5, 10, 4),
'Sum Month 03' = c(9, 6, 5), 'Sum Month 04' = c(5, 9, 10),
'End of Month 01' = rep('10/28/22', 3),
'End of Month 02' = rep('12/02/22', 3),
'End of Month 03' = rep('12/30/22', 3),
'End of Month 04' = rep('01/27/23', 3), check.names = F)
for (i in seq_along(sample.data.frame[grepl("Sum Month", colnames(sample.data.frame))])){
if (substr(sample.data.frame[grepl("End of", colnames(sample.data.frame))][[i]][[1]], 7, 8) > 22){
sample.data.frame[grepl("Sum Month", colnames(sample.data.frame))][[i]] <- 0
}
}
Additionally, I have written the following function based on the code above which works on a vector of dates and a vector of numbers. I can't figure out how to make it work over multiple vectors of dates and numbers (e.g., the various columns of the dataframe).
data.replace.fcn <- function(date.col, number.col){
for (i in seq_along(date.col)) {
if (substr(date.col[i], 7, 8) > 22) {
number.col[i] <- 0
} else {
number.col[i] <- number.col[i]
}
}
return(number.col)
}
Thanks in advance for your help.