Debian Codegraph @

R/rpart.R

raw
1 #
2 # ggdendro/R/dendro_rpart.R by Andrie de Vries and Brian Ripley
3 # Copyright (C) 2011-2015
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 or 3 of the License
8 # (at your option).
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18 #
19
20
21 # labels.rpart ----------------------------------------------------------------
22
23
24 #' Make the nice labels used by print and summary.
25 #'
26 #' @param digits obvious
27 #'
28 #' @param minlength 0 = don't abbrev factors; 1 = use single letters; 2+= the
29 #' same arg as the "abbreviate" function
30 #'
31 #' @param collapse an oddly named argument: FALSE = return a matrix with two
32 #' columns, containing the labels of the left and right descendants of each
33 #' node; TRUE = return a vector of 1 column, with the label of the parent
34 #'
35 #' @param pretty: for historical compatibility: 0 -> minlength = 0; NULL ->
36 #' minlength = 1; TRUE -> minlength = 4
37 #'
38 #' @param ... = other args for abbreviate()
39 #'
40 #' @keywords internal
41 #' @noRd
42 labels.rpart <- function(object, digits = 4, minlength = 1L, pretty,
43 collapse = TRUE, ...) {
44 if (missing(minlength) && !missing(pretty)) {
45 minlength <- if (is.null(pretty)) {
46 1L
47 } else if (is.logical(pretty)) {
48 if (pretty) 4L else 0L
49 } else {
50 0L
51 }
52 }
53
54 ff <- object$frame
55 n <- nrow(ff)
56 if (n == 1L) {
57 return("root")
58 } # special case of no splits
59
60 is.leaf <- (ff$var == "<leaf>")
61 whichrow <- !is.leaf
62 vnames <- ff$var[whichrow] # the variable names for the primary splits
63
64 index <- cumsum(c(1, ff$ncompete + ff$nsurrogate + !is.leaf))
65 irow <- index[c(whichrow, FALSE)] # we only care about the primary split
66 ncat <- object$splits[irow, 2L]
67
68 ## Now to work: first create labels for the left and right splits,
69 ## but not for leaves of course
70 ##
71 lsplit <- rsplit <- character(length(irow))
72
73 if (any(ncat < 2L)) { # any continuous vars ?
74 jrow <- irow[ncat < 2L]
75 cutpoint <- formatg(object$splits[jrow, 4L], digits)
76 temp1 <- (ifelse(ncat < 0, "< ", ">="))[ncat < 2L]
77 temp2 <- (ifelse(ncat < 0, ">=", "< "))[ncat < 2L]
78 lsplit[ncat < 2L] <- paste0(temp1, cutpoint)
79 rsplit[ncat < 2L] <- paste0(temp2, cutpoint)
80 }
81
82 if (any(ncat > 1L)) { # any categorical variables ?
83 xlevels <- attr(object, "xlevels")
84 ##
85 ## jrow will be the row numbers of factors within lsplit and rsplit
86 ## crow the row number in "csplit"
87 ## and cindex the index on the "xlevels" list
88 ##
89 jrow <- seq_along(ncat)[ncat > 1L]
90 crow <- object$splits[irow[ncat > 1L], 4L] # row number in csplit
91 cindex <- (match(vnames, names(xlevels)))[ncat > 1L]
92
93 ## Now, abbreviate the levels
94 if (minlength == 1L) {
95 if (any(ncat > 52L)) {
96 warning("more than 52 levels in a predicting factor, truncated for printout",
97 domain = NA
98 )
99 }
100 xlevels <- lapply(xlevels, function(z) c(letters, LETTERS)[pmin(seq_along(z), 52L)])
101 } else if (minlength > 1L) {
102 xlevels <- lapply(xlevels, abbreviate, minlength, ...)
103 }
104
105 ## Now tuck in the labels
106 ## I'll let some other clever person vectorize this
107 for (i in seq_along(jrow)) {
108 j <- jrow[i]
109 splits <- object$csplit[crow[i], ]
110 ## splits will contain 1=left, 3=right, 2= neither
111 cl <- if (minlength == 1L) "" else ","
112 lsplit[j] <-
113 paste((xlevels[[cindex[i]]])[splits == 1L], collapse = cl)
114 rsplit[j] <-
115 paste((xlevels[[cindex[i]]])[splits == 3L], collapse = cl)
116 }
117 }
118
119 if (!collapse) { # called by no routines that I know of
120 ltemp <- rtemp <- rep("<leaf>", n)
121 ltemp[whichrow] <- lsplit
122 rtemp[whichrow] <- rsplit
123 return(cbind(ltemp, rtemp))
124 }
125
126 lsplit <- paste0(ifelse(ncat < 2L, "", "="), lsplit)
127 rsplit <- paste0(ifelse(ncat < 2L, "", "="), rsplit)
128
129 ## Now match them up to node numbers
130 ## The output will have one label per row of object$frame, each
131 ## corresponding the the line segement joining this node to its parent
132 varname <- (as.character(vnames))
133 node <- as.numeric(row.names(ff))
134 parent <- match(node %/% 2L, node[whichrow])
135 odd <- (as.logical(node %% 2L))
136
137 labels <- character(n)
138 labels[odd] <- paste0(varname[parent[odd]], rsplit[parent[odd]])
139 labels[!odd] <- paste0(varname[parent[!odd]], lsplit[parent[!odd]])
140 labels[1L] <- "root"
141 labels
142 }
143
144
145 # rpart_ggdendro_env ------------------------------------------------------
146
147 # rpart_ggdendro_env <- new.env()
148
149
150 # rpart.branch ------------------------------------------------------------
151
152
153
154 ##
155 ## Compute the "branches" to be drawn for an rpart object
156 ##
157 ## most likely this could simply default to branch = 1
158 rpart.branch <- function(x, y, node, branch) {
159 # if (missing(branch)) {
160 # pn <- paste0("device", dev.cur())
161 # if (!exists(pn, envir = rpart_ggdendro_env, inherits = FALSE))
162 # stop("no information available on parameters from previous call to plot()")
163 # parms <- get(pn, envir = rpart_ggdendro_env, inherits = FALSE)
164 # branch <- parms$branch
165 # }
166 if (missing(branch)) branch <- 1
167
168 ## Draw a series of horseshoes, left son, up, over, down to right son
169 ## NA's in the vector cause lines() to "lift the pen"
170 is.left <- (node %% 2L == 0L) # left hand sons
171 node.left <- node[is.left]
172 parent <- match(node.left / 2L, node)
173 sibling <- match(node.left + 1L, node)
174 temp <- (x[sibling] - x[is.left]) * (1 - branch) / 2
175 xx <- rbind(
176 x[is.left], x[is.left] + temp,
177 x[sibling] - temp, x[sibling], NA
178 )
179 yy <- rbind(y[is.left], y[parent], y[parent], y[sibling], NA)
180 list(x = xx, y = yy)
181 }
182
183
184 # tree.depth ------------------------------------------------------------------
185
186 tree.depth <- function(nodes) {
187 depth <- floor(log(nodes, base = 2) + 1e-7)
188 depth - min(depth)
189 }
190
191
192 # rpartco ---------------------------------------------------------------------
193
194 #' Compute the x-y coordinates for a tree.
195 #'
196 #' @param tree Tree model
197 #' @param parms Graphics parameters
198 #' @keywords internal
199 rpartco <- function(tree, parms) {
200 # if (missing(parms)) {
201 # pn <- paste0("device", dev.cur())
202 # if (!exists(pn, envir = rpart_ggdendro_env, inherits = FALSE))
203 # stop("no information available on parameters from previous call to plot()")
204 # parms <- get(pn, envir = rpart_ggdendro_env, inherits = FALSE)
205 # }
206
207 frame <- tree$frame
208 node <- as.numeric(row.names(frame))
209 depth <- tree.depth(node)
210 is.leaf <- (frame$var == "<leaf>")
211 if (length(parms)) {
212 uniform <- parms$uniform
213 nspace <- parms$nspace
214 minbranch <- parms$minbranch
215 } else {
216 uniform <- FALSE
217 nspace <- -1
218 minbranch <- 0.3
219 }
220
221 if (uniform) {
222 y <- (1 + max(depth) - depth) / max(depth, 4L)
223 } else { # make y- (parent y) = change in deviance
224 y <- dev <- frame$dev
225 temp <- split(seq(node), depth) # depth 0 nodes, then 1, then ...
226 parent <- match(node %/% 2L, node)
227 sibling <- match(ifelse(node %% 2L, node - 1L, node + 1L), node)
228
229 ## assign the depths
230 for (i in temp[-1L]) {
231 temp2 <- dev[parent[i]] - (dev[i] + dev[sibling[i]])
232 y[i] <- y[parent[i]] - temp2
233 }
234 ##
235 ## For some problems, classification & loss matrices in particular
236 ## the gain from a split may be 0. This is ugly on the plot.
237 ## Hence the "fudge" factor of 0.3 * the average step
238 ##
239 fudge <- minbranch * diff(range(y)) / max(depth)
240 for (i in temp[-1L]) {
241 temp2 <- dev[parent[i]] - (dev[i] + dev[sibling[i]])
242 haskids <- !(is.leaf[i] & is.leaf[sibling[i]])
243 y[i] <- y[parent[i]] - ifelse(temp2 <= fudge & haskids, fudge, temp2)
244 }
245 y <- y / (max(y))
246 }
247
248 # Now compute the x coordinates, by spacing out the leaves and then
249 # filling in
250 x <- double(length(node)) # allocate, then fill it in below
251 x[is.leaf] <- seq(sum(is.leaf)) # leaves at 1, 2, 3, ....
252 left.child <- match(node * 2L, node)
253 right.child <- match(node * 2L + 1L, node)
254
255 ## temp is a list of non-is.leaf, by depth
256 temp <- split(seq(node)[!is.leaf], depth[!is.leaf])
257 for (i in rev(temp)) {
258 x[i] <- 0.5 * (x[left.child[i]] + x[right.child[i]])
259 }
260
261 if (nspace < 0) {
262 return(list(x = x, y = y))
263 }
264
265 ##
266 ## Now we get fancy, and try to do overlapping
267 ##
268 ## The basic algorithm is, at each node:
269 ## 1: get the left & right edges, by depth, for the left and
270 ## right sons, of the x-coordinate spacing.
271 ## 2: find the minimal free spacing. If this is >0, slide the
272 ## right hand son over to the left
273 ## 3: report the left & right extents of the new tree up to the
274 ## parent
275 ## A way to visualize steps 1 and 2 is to imagine, for a given node,
276 ## that the left son, with all its descendants, is drawn on a
277 ## slab of wood. The left & right edges, per level, give the
278 ## width of this board. (The board is not a rectangle, it has
279 ## 'stair step' edges). Do the same for the right son. Now
280 ## insert some spacers, one per level, and slide right hand
281 ## board over until they touch. Glue the boards and spacer
282 ## together at that point.
283 ##
284 ## If a node has children, its 'space' is considered to extend left
285 ## and right by the amount "nspace", which accounts for space
286 ## used by the arcs from this node to its children. For
287 ## horseshoe connections nspace usually is 1.
288 ##
289 compress <- function(x, me, depth) {
290 lson <- me + 1L
291 if (is.leaf[lson]) {
292 left <- list(
293 left = x[lson], right = x[lson],
294 depth = depth + 1L, sons = lson
295 )
296 } else {
297 left <- compress(x, me + 1L, depth + 1L)
298 x <- left$x
299 }
300
301 rson <- me + 1L + length(left$sons) # index of right son
302 if (is.leaf[rson]) {
303 right <- list(
304 left = x[rson], right = x[rson],
305 depth = depth + 1L, sons = rson
306 )
307 } else {
308 right <- compress(x, rson, depth + 1L)
309 x <- right$x
310 }
311
312 maxd <- max(left$depth, right$depth) - depth
313 mind <- min(left$depth, right$depth) - depth
314
315 ## Find the smallest distance between the two subtrees
316 ## But only over depths that they have in common
317 ## 1 is a minimum distance allowed
318 slide <- min(right$left[1L:mind] - left$right[1L:mind]) - 1L
319 if (slide > 0) { # slide the right hand node to the left
320 x[right$sons] <- x[right$sons] - slide
321 x[me] <- (x[right$sons[1L]] + x[left$sons[1L]]) / 2
322 }
323 else {
324 slide <- 0
325 }
326
327 ## report back
328 if (left$depth > right$depth) {
329 templ <- left$left
330 tempr <- left$right
331 tempr[1L:mind] <- pmax(tempr[1L:mind], right$right - slide)
332 } else {
333 templ <- right$left - slide
334 tempr <- right$right - slide
335 templ[1L:mind] <- pmin(templ[1L:mind], left$left)
336 }
337
338 list(
339 x = x,
340 left = c(x[me] - nspace * (x[me] - x[lson]), templ),
341 right = c(x[me] - nspace * (x[me] - x[rson]), tempr),
342 depth = maxd + depth, sons = c(me, left$sons, right$sons)
343 )
344 }
345 x <- compress(x, 1L, 1L)$x
346 list(x = x, y = y)
347 }
348
349
350 # text.rpart ------------------------------------------------------------------
351
352 ## This is a modification of text.tree.
353 ## Fancy option has been added in (to mimic post.tree)
354 ##
355
356 text_rpart <- function(x, splits = TRUE, label, FUN = text, all = FALSE,
357 pretty = NULL, digits = getOption("digits") - 3L,
358 use.n = FALSE, fancy = FALSE, fwidth = 0.8, fheight = 0.8,
359 bg = par("bg"), minlength = 1L, parms, ...) {
360 string.bounding.box <- NULL
361 if (!inherits(x, "rpart")) stop("Not a legitimate \"rpart\" object")
362 if (nrow(x$frame) <= 1L) stop("fit is not a tree, just a root")
363
364 frame <- x$frame
365 if (!missing(label)) warning("argument 'label' is no longer used")
366 col <- names(frame)
367 ylevels <- attr(x, "ylevels")
368 if (!is.null(ylevels <- attr(x, "ylevels"))) col <- c(col, ylevels)
369 # cxy <- par("cxy") # character width and height
370 cxy <- c(0.1, 0.1)
371 if (!is.null(srt <- list(...)$srt) && srt == 90) cxy <- rev(cxy)
372 xy <- rpartco(x, parms = parms)
373
374 node <- as.numeric(row.names(frame))
375 is.left <- (node %% 2L == 0L) # left hand sons
376 node.left <- node[is.left]
377 parent <- match(node.left / 2L, node)
378
379 ## Put left splits at the parent node
380 if (splits) {
381 left.child <- match(2L * node, node)
382 right.child <- match(node * 2L + 1L, node)
383 rows <- if (!missing(pretty) && missing(minlength)) {
384 labels(x, pretty = pretty)
385 } else {
386 labels(x, minlength = minlength)
387 }
388 if (fancy) {
389 ## put split labels on branches instead of nodes
390 xytmp <- rpart.branch(x = xy$x, y = xy$y, node = node)
391 leftptx <- (xytmp$x[2L, ] + xytmp$x[1L, ]) / 2
392 leftpty <- (xytmp$y[2L, ] + xytmp$y[1L, ]) / 2
393 rightptx <- (xytmp$x[3L, ] + xytmp$x[4L, ]) / 2
394 rightpty <- (xytmp$y[3L, ] + xytmp$y[4L, ]) / 2
395
396 # FUN(leftptx, leftpty + 0.52 * cxy[2L],
397 # rows[left.child[!is.na(left.child)]], ...)
398 # FUN(rightptx, rightpty - 0.52 * cxy[2L],
399 # rows[right.child[!is.na(right.child)]], ...)
400 } else {
401 # FUN(xy$x, xy$y + 0.5 * cxy[2L], rows[left.child], ...)
402
403 ### Insertion by Andrie de Vries to capture label splits
404 labelSplits <- data.frame(
405 x = xy$x,
406 y = xy$y,
407 label = rows[left.child]
408 )
409 }
410 labelSplits <- labelSplits[complete.cases(labelSplits), ]
411 labelSplits$type <= "splits"
412 }
413
414 leaves <- if (all) rep(TRUE, nrow(frame)) else frame$var == "<leaf>"
415
416 stat <-
417 x$functions$text(
418 yval = if (is.null(frame$yval2)) {
419 frame$yval[leaves]
420 } else {
421 frame$yval2[leaves, ]
422 },
423 dev = frame$dev[leaves], wt = frame$wt[leaves],
424 ylevel = ylevels, digits = digits,
425 n = frame$n[leaves], use.n = use.n
426 )
427
428 # if (fancy) {
429 # if (col2rgb(bg, alpha = TRUE)[4L, 1L] < 255) bg <- "white"
430 # oval <- function(middlex, middley, a, b)
431 # {
432 # theta <- seq(0, 2 * pi, pi/30)
433 # newx <- middlex + a * cos(theta)
434 # newy <- middley + b * sin(theta)
435 # polygon(newx, newy, border = TRUE, col = bg)
436 # }
437 #
438 # ## FIXME: use rect()
439 # rectangle <- function(middlex, middley, a, b)
440 # {
441 # newx <- middlex + c(a, a, -a, -a)
442 # newy <- middley + c(b, -b, -b, b)
443 # polygon(newx, newy, border = TRUE, col = bg)
444 # }
445 #
446 # ## find maximum length of stat
447 # maxlen <- max(string.bounding.box(stat)$columns) + 1L
448 # maxht <- max(string.bounding.box(stat)$rows) + 1L
449 #
450 # a.length <- if (fwidth < 1) fwidth * cxy[1L] * maxlen else fwidth * cxy[1L]
451 #
452 # b.length <- if (fheight < 1) fheight * cxy[2L] * maxht else fheight * cxy[2L]
453 #
454 # ## create ovals and rectangles here
455 # ## sqrt(2) creates the smallest oval that fits around the
456 # ## best fitting rectangle
457 # for (i in parent)
458 # oval(xy$x[i], xy$y[i], sqrt(2) * a.length/2, sqrt(2) * b.length/2)
459 # child <- match(node[frame$var == "<leaf>"], node)
460 # for (i in child)
461 # rectangle(xy$x[i], xy$y[i], a.length/2, b.length/2)
462 # }
463
464 ## if FUN=text then adj=1 puts the split label to the left of the
465 ## split rather than centered
466 ## Allow labels at all or just leaf nodes
467
468 ## stick values on nodes
469 # if (fancy) FUN(xy$x[leaves], xy$y[leaves] + 0.5 * cxy[2L], stat, ...)
470 # else FUN(xy$x[leaves], xy$y[leaves] - 0.5 * cxy[2L], stat, adj = 0.5, ...)
471 labelLeaves <- data.frame(
472 x = xy$x[leaves],
473 y = xy$y[leaves],
474 label = stat
475 )
476
477
478
479 # return(list(xy=xy, cxy=cxy))
480 list(
481 labels = labelSplits,
482 leaf_labels = labelLeaves
483 )
484 }
485
486
487
488 # formatg -----------------------------------------------------------------
489
490
491
492 ## format a set of numbers using C's "g" format
493 ## No longer exported.
494 formatg <- function(x, digits = getOption("digits"),
495 format = paste0("%.", digits, "g")) {
496 if (!is.numeric(x)) stop("'x' must be a numeric vector")
497
498 temp <- sprintf(format, x)
499 if (is.matrix(x)) matrix(temp, nrow = nrow(x)) else temp
500 }