Home > database >  How adjust code functionality to specifications using data.table function
How adjust code functionality to specifications using data.table function

Time:04-22

I would like to change the approach to generating Output. Is it possible to use the data.table function for this case below? If yes, could you help me adjust? I have inserted an example below of the calculation that is done. The code below is from an already resolved question: How to adjust specifications for output table generation

library(dplyr)
library(tidyverse)
library(lubridate)


df1 <- structure(list(date1 = c("2021-06-28"), 
                      date2 = c("2021-06-30"), 
                      Category = c("FDE"), 
                      Week = c("Wednesday"), 
                      DR1 = c(4), DRM001 = c(4), DRM002 = c(2), 
                      DRM003 = c(9), DRM004 = c(5), DRM005 = c(5), 
                      DRM006 = c(2),DRM007 = c(1),
                      coef = c(8)), class = "data.frame", row.names = c(NA, -1L))


Output<-df1 %>% 
  mutate(across(starts_with("DR"), ~ coef - .),
         across(contains("date"), ymd),
         datedif = parse_number(as.character(date2-date1))
  ) %>% 
  rename_with(~str_replace(.,'(?<=[A-Z])0 (?=.)', ""),starts_with('DR')) %>% 
  rowwise %>%
  mutate(Result = if (str_c('DRM', datedif) %in% names(.)) get(str_c('DRM', datedif)) else coef) %>%
  ungroup() %>% 
  select(coef, Result)%>           
  • Related