Home > database >  modification of lists with respect to dates
modification of lists with respect to dates

Time:11-29

I have a list data

list <- list()
list$date <- structure(19297:19310, class = "Date")
list$value <- c(100,200,300,100,200,300,100,200,300,100,200,500,800)
list$temp2 <- c(1000,2000,3000,1000,2000,3000,1000,2000,3000,1000,2000,5888,9887)

I want to modify the list in such a way that:

  • every element of the list$value is multiplied with 0.5 * list$temp2 (which can be done by a multiply operation)
  • Except the maximum of the value that is in between days 1 to 7 of the date (maximum of first week) - this maximum value needs to be doubled. (i.e., only one list$value doesn't get replaced with the step 1 rather is doubled by its own value)

Can anyone help me with this?

CodePudding user response:

Converting the list into a data.frame (or better yet a data.table) will enable column-wise operations on the data.

dl <- list()
dl$date <- structure(19297:19310, class = "Date")
dl$value <- c(100,200,300,100,200,300,100,200,300,100,200,500,800)
dl$temp2 <- c(1000,2000,3000,1000,2000,3000,1000,2000,3000,1000,2000,5888,9887)

Since the list elements are unequal length, adding NAs to the end, so there are 14 elements in each value

dl$value[[length(dl$value) 1]] <- NA
dl$temp2[[length(dl$temp2) 1]] <- NA

Convert to a data.frame

df <- as.data.frame(dl)

Create the exception criteria (max value of the first 7 days)

df$exception <- df$value == max(df[1:7,"value"])
df$exception[is.na(df$exception)] <- FALSE

Create a new variable "value2" and perform the multiplications .5 where the exception doesn't occur, and x2 where it does occur.

df$value2 <- as.numeric(NA)
df$value2[df$exception == FALSE] <- df$value[df$exception == FALSE] * 0.5
df$value2[df$exception == TRUE] <- df$value[df$exception == TRUE] * 2

The output, which can be passed back into a list object, if required

df$date
df$value2
df$temp2
  • Related