@@ -324,6 +324,45 @@ ppc_error_scatter_avg_vs_x <- function(
324324 coord_flip()
325325}
326326
327+ # ' @rdname PPC-errors
328+ # ' @export
329+ ppc_residual_scatter <- function (
330+ y ,
331+ yrep ,
332+ x = NULL ,
333+ ... ,
334+ stat = " mean" ,
335+ facet_args = list (),
336+ size = 2.5 ,
337+ alpha = 0.8 ) {
338+ check_ignored_arguments(... )
339+
340+ y <- validate_y(y )
341+ yrep <- validate_predictions(yrep , length(y ))
342+
343+ if (! missing(x )) {
344+ qx <- enquo(x )
345+ x <- validate_x(x , y )
346+ }
347+
348+ stat <- as_tagged_function({{ stat }})
349+ residuals <- compute_residuals(y , yrep , stat )
350+ stat_yrep <- apply(yrep , 2 , stat )
351+
352+ ppc_scatter(
353+ y = if (is_null(x )) stat_yrep else x ,
354+ yrep = residuals ,
355+ facet_args = facet_args ,
356+ size = size ,
357+ alpha = alpha ,
358+ ref_line = FALSE
359+ ) +
360+ labs(
361+ x = residual_label(stat ),
362+ y = if (is_null(x )) y_label() else as_label((qx ))
363+ ) + coord_flip()
364+ }
365+
327366
328367# ' @rdname PPC-errors
329368# ' @export
@@ -415,6 +454,19 @@ compute_errors <- function(y, yrep) {
415454 rstantools :: predictive_error(object = yrep , y = y )
416455}
417456
457+ # ' Compute predictive residuals `y` - `stat(yrep)`
458+ # ' @noRd
459+ # ' @param y,yrep User's `y` and `yrep` arguments.
460+ # ' @param stat Function or string to compute statistic
461+ # ' across the draws for each data point.
462+ # ' @return A vector of residuals, one for each observation
463+ compute_residuals <- function (y , yrep , stat ) {
464+ yrep_stat <- apply(yrep , 2 , stat )
465+ residuals <- y - yrep_stat
466+ residuals <- matrix (residuals , nrow = 1 )
467+ return (residuals )
468+ }
469+
418470
419471# ' Create facet layer for PPC error plots
420472# '
@@ -473,6 +525,22 @@ error_avg_label <- function(stat = NULL) {
473525 expr(paste((!! de ))* (italic(y ) - italic(y )[rep ]))
474526}
475527
528+ residual_label <- function (stat = NULL ) {
529+ stat <- as_tagged_function({{ stat }}, fallback = " stat" )
530+ e <- attr(stat , " tagged_expr" )
531+ if (attr(stat , " is_anonymous_function" )) {
532+ e <- sym(" stat" )
533+ }
534+ de <- deparse1(e )
535+
536+ # create some dummy variables to pass the R package check for
537+ # global variables in the expression below
538+ italic <- sym(" italic" )
539+ y <- sym(" y" )
540+
541+ expr(paste(italic(y ) - (!! de )* (italic(y )[rep ])))
542+ }
543+
476544
477545# Data for binned errors plots
478546ppc_error_binnned_data <- function (y , yrep , x = NULL , bins = NULL ) {
0 commit comments