I have a list in lists
list1 <- list()
list1$date <- c("01/06/2002", "02/06/2002", "03/06/2002",
"04/06/2002", "05/06/2002", "01/07/2002", "19/07/2002", "11/07/2002",
"15/07/2002", "29/07/2002", "03/07/2002")
list1$value1 <- c(100,200,300,100,200,300,100,200,300,100,200)
I am trying to scale the "value1" which is maximum during the first week and also the last 2 days of the month. That is:
- if the value is in between the dates 01 and 07 - only the maximum of the value must be doubled
- If the date is >=28 then also the value needs to be doubled
Is there way where I can do this?
CodePudding user response:
The lubridate package provides a variety of convenient date functions
library(lubridate)
list1 <- list()
list1$date <- c("01/06/2002", "02/06/2002", "03/06/2002",
"04/06/2002", "05/06/2002", "01/07/2002", "19/07/2002", "11/07/2002",
"15/07/2002", "29/07/2002", "03/07/2002")
list1$value1 <- c(100,200,300,100,200,300,100,200,300,100,200)
The list1$date object are strings, to use lubrdate's dmy (for day-month-year) to convert into a Date class, and then use the day() function to extract the numeric date of the month.
Assign to the doubles variable the dates that are in the first weeek (ie, less than day 7) or after day 28.
first7 <- day(dmy(list1$date)) <= 7
after28 <- day(dmy(list1$date)) >= 28
doubles <- (first7 & list1$value1 == max(list1$value1[first7],na.rm=T)) | after28
Assign to a coefficients variable the values that meet the doubles criteria and those that do not (simply multiply by 1).
coefficients <- ifelse(doubles,2,1)
Multiply the list1$value by the coefficients to get the required result
list1$value1 * coefficients