Home > database >  modify lists based on dates
modify lists based on dates

Time:11-28

Hello I have list in lists data

list1 <- list()

#date list is a "date" object
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", "17/07/2002", "03/07/2002")

list1$value1 <- c(100,200,300,100,200,300,100,200,300,100,200)

list1$value2 <- c(1000,2000,3000,1000,2000,3000,1000,2000,3000,1000,2000)

I want to modify the values in the list such that if the dates are in between 1 and 7 - the list values get doubled.

Is there a way where I can write a condition that checks the day of the list and doubles the value in the other lists?

Expected Output:

 list$value1 
 c(200,400,600,200,400,600,100,200,300,100,400)
    
 list$value2 
 c(2000,4000,6000,2000,4000,6000,1000,2000,3000,1000,4000)

CodePudding user response:

You may get the dates extracting first 2 characters and use lapply to double the values where the dates are between 1 and 7.

inds <- as.integer(substr(list1$date, 1, 2)) <= 7
#List names that needs to be changed
nm <- c('value1', 'value2')
list1[nm] <- lapply(list1[nm], function(x) {x[inds] <- x[inds] * 2;x})
list1

#$date
# [1] "01/06/2002" "02/06/2002" "03/06/2002" "04/06/2002" "05/06/2002" "01/07/2002"
# [7] "19/07/2002" "11/07/2002" "15/07/2002" "17/07/2002" "03/07/2002"

#$value1
# [1] 200 400 600 200 400 600 100 200 300 100 400

#$value2
# [1] 2000 4000 6000 2000 4000 6000 1000 2000 3000 1000 4000

data

There were some missing quotation in the data, fixing that and change the name of the list to list1 since list is a name of the function.

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", "17/07/2002", "03/07/2002")

list1$value1 <- c(100,200,300,100,200,300,100,200,300,100,200)

list1$value2 <- c(1000,2000,3000,1000,2000,3000,1000,2000,3000,1000,2000)

CodePudding user response:

You can extract the day using as.numeric(strftime()), and replace values conditionally with ifelse():

for (val in c("value1", "value2")) {
  List[[val]] <- ifelse(
    as.numeric(strftime(List[["date"]], "%d")) <= 7,
    List[[val]] * 2,
    List[[val]]
  )
}

List[c("value1", "value2")]
$value1
 [1] 200 400 600 200 400 600 100 200 300 100 400

$value2
 [1] 2000 4000 6000 2000 4000 6000 1000 2000 3000 1000 4000
  • Related