Dear Everyone,

I am currently trying to calculate a new variable (both dummy and absolute) called Bath in R, but I seem to get the following error:

Error: Internal error: Trace data is not square.

Does anyone know how I can fix this error and/or another method that lets me define this variable.

I have a reprex down below:

library(dplyr)

gvkey <- c(1, 1, 1, 1, 2,2,2, 4, 4 )

fyear <- c(2005,2006,2007,2008, 2007,2008,2009 , 2011,2012)

nibi <- c(100, 110, 120, 130, 500, 550, 600, 50, 60)

lagAT <- c(1000,1500,1300,1200, 300,500, 800, 70, 40)Thesis <- data.frame(gvkey, fyear, nibi, lagAT)

Thesis <- Thesis%>%

group_by(gvkey) %>%

arrange(fyear) %>%

mutate(Bath= Thesis %>% filter((nibi -lag(nibi)) /lagAT<0) %>%

mutate(BATH = if_else(((nibi -lag(nibi)) /lagAT)< median((nibi -lag(nibi)) /lagAT,

na.rm = TRUE), (nibi-lag(nibi))/lagAT, 0),

dBATH = if_else(((nibi -lag(nibi)) /lagAT)< median((nibi -lag(nibi)) /lagAT,

na.rm = TRUE), 1, 0)) %>%

select(gvkey, fyear,BATH, dBATH, nibi, lagAT, nibi-lag(nibi)))