0

My goal is to take a subset of columns (COL_NAMES) within a dataframe (LR_DATA) and apply a function (FUNCTION). The dataframe (LR_DATA) is mostly nested vectors except for one identifying column (var1). However, I cannot seem to correctly pass the override inputs which are nested under the current column name with the additional suffix "_OVERRIDE".

TRENDED_LR_DATA <- LR_DATA %>% mutate(across(all_of(COL_NAMES), ~list(FUNCTION(var1, unlist(var2), unlist(.x), unlist(!!sym(paste0(cur_column(), "_OVERRIDE")))))))

Specifically I get the error: "Error in local_error context(dots = dots, .index = i, mask = mask

If I replace cur_column() with a hardcoded string the code works (though obviously not as intended since it would be referencing the same override column for each specified column in COL_NAMES. Any tips this group has would be greatly appreciated - I'm relatively new to R so please bear with me ^_^.

EDIT: Below is code to reproduce the error in full. Sorry for not including this on the original question submission.

library(dplyr)

LR_DATA <- data.frame(STATE = c(1,2,3),
                      YEAR = c(2000,2001,2002),
                      DEVT_A = c(2,4,6),
                      DEVT_B = c(3,6,9),
                      DEVT_C = c(4,8,12))

LOSS_COLS <- c("DEVT_A", "DEVT_B", "DEVT_C")

DATA_OVERRIDE <- data.frame(STATE = c(1,2,3),
                            DEVT_A_OVERRIDE = c(NaN,1,1),
                            DEVT_B_OVERRIDE = c(1,1,1),
                            DEVT_C_OVERRIDE = c(1.5,1.5,1.5))

LR_DATA <- LR_DATA %>% left_join(DATA_OVERRIDE, by = 'STATE')

TRENDED_LR_DATA <- LR_DATA %>% summarise(across(everything(), list), .groups = "keep") %>%
  mutate(across(all_of(LOSS_COLS), ~list(TREND_LOSS(unlist(.x), unlist(YEAR), unlist( !!sym(paste0(cur_column(), "_OVERRIDE"))) )))) 

TREND_LOSS <- 
  
  function(LOSSES, 
           YEARS,
           OVERRIDES) {
      
  x <- YEARS
  y = log(LOSSES)
  xy = x * y
  x_sq = x * x
  sum_x <- sum(x)
  sum_y <- sum(y)
  sum_xy <- sum(xy)
  sum_x_sq <- sum(x_sq)
  n <- length(YEARS)
  Slope <- (n*sum_xy - sum_x*sum_y) / (n*sum_x_sq - sum_x*sum_x)
  
  OVERRIDES[is.na(OVERRIDES)] <- Slope
  TRENDED_LOSSES <- LOSSES*exp(OVERRIDES)
  return(TRENDED_LOSSES)
  
  }
  
}
moo5003
  • 19
  • 4
  • 2
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 12 '22 at 21:55
  • I added code to reproduce the error in full. Thanks in advance for any help you can provide. – moo5003 Aug 15 '22 at 15:49

0 Answers0