File: utils.R

package info (click to toggle)
r-cran-mlr 2.19.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,264 kB
  • sloc: ansic: 65; sh: 13; makefile: 5
file content (64 lines) | stat: -rw-r--r-- 1,861 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
# get one el from each row of a matrix, given indices or col names (factors for colnames are converted to characters)
getRowEls = function(mat, inds) {
  if (is.factor(inds)) {
    inds = as.character(inds)
  }
  if (is.character(inds)) {
    inds = match(inds, colnames(mat))
  }
  inds = cbind(seq_row(mat), inds)
  mat[inds]
}

# get one el from each col of a matrix, given indices or row names
getColEls = function(mat, inds) {
  getRowEls(t(mat), inds)
}

# Do fuzzy string matching between input and a set of valid inputs
# and return the most similar valid inputs.
getNameProposals = function(input, possible.inputs, nproposals = 3L) {

  assertString(input)
  assertCharacter(possible.inputs)
  assertInt(nproposals, lower = 1L)

  # compute the approximate string distance (using the generalized Levenshtein / edit distance)
  # and get the nproposals most similar valid inputs.
  indices = order(adist(input, possible.inputs))[1:nproposals]
  possibles = na.omit(possible.inputs[indices])
  return(possibles)
}

# shorter way of printing debug dumps
#' @export
print.mlr.dump = function(x, ...) {
  cat("<debug dump>\n")
  invisible(NULL)
}


# applys the appropriate getPrediction* helper function
getPrediction = function(object, newdata, ...) {
  pred = do.call("predict", c(list("object" = object, "newdata" = newdata), list(...)))
  point = switch(object$task.desc$type,
    "regr" = getPredictionResponse(pred),
    "surv" = getPredictionResponse(pred),
    "classif" = if (object$learner$predict.type == "response") {
      getPredictionResponse(pred)
    } else {
      getPredictionProbabilities(pred)
    }
  )

  if (object$learner$predict.type == "se") {
    cbind("preds" = point, "se" = getPredictionSE(pred))
  } else {
    point
  }
}

# replacement for purrr::imap()
imap = function(.x, .f) {
  Map(.f, .x = .x, .y = seq_along(.x))
}