File: plot_model_estimates.R

package info (click to toggle)
r-cran-sjplot 2.8.17%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,596 kB
  • sloc: sh: 13; makefile: 2
file content (293 lines) | stat: -rw-r--r-- 8,535 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
plot_model_estimates <- function(model,
                                 dat,
                                 tf,
                                 se,
                                 terms,
                                 group.terms,
                                 rm.terms,
                                 sort.est,
                                 title,
                                 axis.title,
                                 axis.labels,
                                 axis.lim,
                                 grid.breaks,
                                 show.intercept,
                                 show.values,
                                 show.p,
                                 value.offset,
                                 digits,
                                 geom.colors,
                                 geom.size,
                                 line.size,
                                 bpe.style,
                                 bpe.color,
                                 term.order,
                                 vline.color,
                                 value.size,
                                 facets,
                                 p.threshold,
                                 ci.style,
                                 ...) {

  # remove intercept(s) from output

  if (!show.intercept) {
    ints1 <- string_contains("(Intercept", x = dat$term)
    ints2 <- string_contains("b_Intercept", x = dat$term)
    ints3 <- string_contains("b_zi_Intercept", x = dat$term)
    ints4 <- which(dat$term %in% "Intercept")

    ints <- c(ints1, ints2, ints3, ints4)

    if (!sjmisc::is_empty(ints))
      dat <- dplyr::slice(dat, !! -ints)
  }


  # remove non-coefficients

  noncoef <- string_contains("Log(theta)", x = dat$term)
  if (!sjmisc::is_empty(noncoef)) dat <- dplyr::slice(dat, !! -noncoef)


  # exponentiation

  if (!is.null(tf) && !is.stan(model)) {

    # no transformation if standard errors should be reported
    # instead of conf. int.

    if (isTRUE(se)) {
      message("If standard errors are requested, no transformation is applied to estimates.")
      tf <- NULL
    } else {
      funtrans <- match.fun(tf)
      dat[["estimate"]] <- funtrans(dat[["estimate"]])
      dat[["conf.low"]] <- funtrans(dat[["conf.low"]])
      dat[["conf.high"]] <- funtrans(dat[["conf.high"]])
    }

  }


  # use standard error instead of ci's?

  if (isTRUE(se)) {
    dat[["conf.low"]] <- dat[["estimate"]] - dat[["std.error"]]
    dat[["conf.high"]] <- dat[["estimate"]] + dat[["std.error"]]
  }


  # remove further estimates

  terms <- parse_terms(terms)
  filter.remove <- dat$term %in% terms
  if (!is.null(terms)) dat <- dplyr::filter(dat, !! filter.remove)


  # or select further estimates

  rm.terms <- parse_terms(rm.terms)
  filter.remove <- !(dat$term %in% rm.terms)
  if (!is.null(rm.terms)) dat <- dplyr::filter(dat, !! filter.remove)


  # add p-asterisks to data

  dat$p.stars <- get_p_stars(dat$p.value, p.threshold)
  dat$p.label <- sprintf("%.*f", digits, dat$estimate)

  if (show.p) dat$p.label <- sprintf("%s %s", dat$p.label, dat$p.stars)


  # create default grouping, depending on the effect:
  # split positive and negative associations with outcome
  # into different groups

  treshold <- dplyr::if_else(isTRUE(tf == "exp"), 1, 0)
  dat$group <- dplyr::if_else(dat$estimate > treshold, "pos", "neg")


  # group estimates?

  if (!is.null(group.terms)) {
    if (length(group.terms) == nrow(dat)) {
      dat$group <- as.character(group.terms)
    } else {
      warning("Length of `group.terms` does not equal number of model coefficients. Ignoring this argument.", call. = F)
      group.terms <- NULL
    }
  }


  # make term name categorical, for axis labelling
  dat$term <- as.factor(dat$term)


  # does user want a specific order for terms?

  ordered.terms <- FALSE
  if (!is.null(term.order)) {
    if (length(term.order) == nrow(dat)) {
      dat$term <- factor(dat$term, levels = unique(dat$term)[rev(term.order)])
      sort.est <- FALSE
      ordered.terms <- TRUE
    } else {
      message("Number of values in `order.terms` does not match number of terms. Terms are not sorted.")
    }
  }


  # sort estimates by effect size

  if (isTRUE(sort.est)) {
    if (!is.null(group.terms))
      dat$term <- factor(dat$term, levels = unique(dat$term[order(dat$group)]))
    else
      dat$term <- factor(dat$term, levels = unique(dat$term[order(dat$estimate)]))
  } else if (!ordered.terms) {
    dat$term <- factor(dat$term, levels = rev(unique(dat$term)))
  }


  # set default colors. for grouped predictors we need more color values

  if (is.null(geom.colors)) geom.colors <- dplyr::if_else(is.null(group.terms), "grey30", "Set1")


  # for brms multilevel with multiple random intercepts, we need
  # special handling

  if (is.stan(model) && stan.has.multiranef(dat)) {
    # split data, create data frame for each random intercept
    dat <- purrr::map(split(dat, f = dat$facet), ~ sjmisc::remove_var(.x, "facet"))

    # random intercept names are default titles
    ri.titles <- names(dat)

    # create plots
    purrr::map2(
      dat,
      1:length(dat),
      function(x, y) {

        # now we need a named vector, in order
        # to match labels and term order at axis

        labs <- as.character(x$term)
        names(labs) <- labs

        # sort terms

        if (!is.null(sort.est)) {
          reihe <- order(x$estimate)
        } else {
          reihe <- 1:nrow(x)
        }
        x$reihe <- order(reihe)

        x$term <- factor(x$term, levels = unique(x$term[order(x$reihe)]))

        # plot title

        if (sjmisc::is_empty(title)) {
          ptitle <- ri.titles[y]
        } else {
          if (length(title) >= y)
            ptitle <- title[y]
          else
            ptitle <- title
        }


        # plot random effects

        plot_point_estimates(
          model = model,
          dat = x,
          tf = tf,
          title = ptitle,
          axis.labels = labs,
          axis.title = NULL,
          axis.lim = axis.lim,
          grid.breaks = grid.breaks,
          show.values = show.values,
          value.offset = value.offset,
          geom.size = geom.size,
          line.size = line.size,
          geom.colors = geom.colors,
          vline.color = vline.color,
          value.size = value.size,
          facets = facets,
          bpe.style = bpe.style,
          bpe.color = bpe.color,
          ci.style = ci.style,
          ...
        )
      }
    )

  } else {

    if (obj_has_name(dat, "wrap.facet") && dplyr::n_distinct(dat$wrap.facet, na.rm = TRUE) > 1 && !facets) {

      dat <- purrr::map(split(dat, f = dat$wrap.facet), ~ sjmisc::remove_var(.x, "wrap.facet"))

      if (length(axis.title) == 1) axis.title <- c(axis.title, "Odds Ratios")

      purrr::pmap(list(dat, axis.title, names(dat)), function(.x, .y, .z) {

        plot_point_estimates(
          model = model,
          dat = .x,
          tf = tf,
          title = paste0(title, " (", .z, ")"),
          axis.labels = axis.labels,
          axis.title = .y,
          axis.lim = NULL,
          grid.breaks = NULL,
          show.values = show.values,
          value.offset = value.offset,
          geom.size = geom.size,
          line.size = line.size,
          geom.colors = geom.colors,
          bpe.style = bpe.style,
          bpe.color = bpe.color,
          vline.color = vline.color,
          value.size = value.size,
          facets = facets,
          ci.style = ci.style,
          ...
        )

      })

    } else {

      plot_point_estimates(
        model = model,
        dat = dat,
        tf = tf,
        title = title,
        axis.labels = axis.labels,
        axis.title = axis.title,
        axis.lim = axis.lim,
        grid.breaks = grid.breaks,
        show.values = show.values,
        value.offset = value.offset,
        geom.size = geom.size,
        line.size = line.size,
        geom.colors = geom.colors,
        bpe.style = bpe.style,
        bpe.color = bpe.color,
        vline.color = vline.color,
        value.size = value.size,
        facets = facets,
        ci.style = ci.style,
        ...
      )

    }
  }
}