quantifish / influ2

Bayesian version of the R package influ (https://github.com/trophia/influ) for use with brms models
http://www.quantifish.co.nz/influ2/
Other
3 stars 0 forks source link

Change top-left output for some variable types #14

Open quantifish opened 4 years ago

quantifish commented 4 years ago

Currently the plot_bayesian_cdi function shows the re-scaled raw coefficients for a fixed-effect and the marginal effect for all other variable types. Suggest showing raw coefs for random-effects too. All continous forms (i.e. poly, spline, linear) can show marginal effect for now.

However, in a hurdle model the marginal effect is integrated over both the hurdle and positive value components of the distribution. It would be better to see these separately for each component of the hurdle. This means I'd need to evaluate the poly, spline etc by hand.

quantifish commented 4 years ago

Some code for doing the leg work for poly:

if (any(grepl("poly", coefs$variable))) { is_poly <- TRUE data <- fit$data %>% select(-starts_with("poly")) dmin <- min(data[,group[2]]) dmax <- max(data[,group[2]]) data[,group[2]] <- cut(data[,group[2]], breaks = seq(dmin, dmax, length.out = 20), include.lowest = TRUE)

breaks <- unique(quantile(data[,group[2]], probs = seq(0, 1, length.out = 15)))

# data[,group[2]] <- cut(data[,group[2]], breaks = breaks, include.lowest = TRUE)
data[,group[2]] <- sapply(data[,group[2]], get_midpoint)

d <- fit$data[,group[2]]
z <- poly(d, 3)
x_new <- data.frame(id = 1:length(unique(data[,group[2]])), variable = sort(unique(data[,group[2]])))
x_poly <- poly(x_new$variable, 3, coefs = attr(z, "coefs"))

# Do the matrix multiplication
Xbeta <- matrix(NA, nrow = n_iterations, ncol = nrow(x_poly))
for (i in 1:n_iterations) {
  Xbeta[i,] <- x_poly %*% filter(coefs, .data$iteration == i)$value
}
coefs <- melt(Xbeta, varnames = c("iteration", "id")) %>%
  left_join(x_new, by = "id") %>%
  select(-id)

} else { data <- fit$data %>% mutate_at(vars(matches(group[2])), factor) }