-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathimap.R
More file actions
82 lines (73 loc) · 2.07 KB
/
imap.R
File metadata and controls
82 lines (73 loc) · 2.07 KB
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
#' Apply a function to each element of a vector, and its index
#'
#' `imap(x, ...)`, an indexed map, is short hand for
#' `map2(x, names(x), ...)` if `x` has names, or `map2(x, seq_along(x), ...)`
#' if it does not. This is useful if you need to compute on both the value
#' and the position of an element.
#'
#' @param .f A function, specified in one of the following ways:
#'
#' * A named function, e.g. `paste`.
#' * An anonymous function, e.g. `\(x, idx) x + idx` or
#' `function(x, idx) x + idx`.
#' * A formula, e.g. `~ .x + .y`. Use `.x` to refer to the current element and
#' `.y` to refer to the current index. No longer recommended.
#'
#' `r lifecycle::badge("experimental")`
#'
#' Wrap a function with [in_parallel()] to declare that it should be performed
#' in parallel. See [in_parallel()] for more details.
#' Use of `...` is not permitted in this context.
#' @inheritParams map
#' @return A vector the same length as `.x`.
#' @export
#' @family map variants
#' @examples
#' imap_chr(sample(10), paste)
#'
#' imap_chr(sample(10), \(x, idx) paste0(idx, ": ", x))
#'
#' iwalk(mtcars, \(x, idx) cat(idx, ": ", median(x), "\n", sep = ""))
imap <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2(.x, vec_index(.x), .f, ...)
}
#' @rdname imap
#' @export
imap_lgl <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2_lgl(.x, vec_index(.x), .f, ...)
}
#' @rdname imap
#' @export
imap_chr <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2_chr(.x, vec_index(.x), .f, ...)
}
#' @rdname imap
#' @export
imap_int <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2_int(.x, vec_index(.x), .f, ...)
}
#' @rdname imap
#' @export
imap_dbl <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2_dbl(.x, vec_index(.x), .f, ...)
}
#' @rdname imap
#' @export
imap_vec <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
map2_vec(.x, vec_index(.x), .f, ...)
}
#' @export
#' @rdname imap
iwalk <- function(.x, .f, ...) {
.f <- as_mapper(.f, ...)
walk2(.x, vec_index(.x), .f, ...)
}
vec_index <- function(x) {
names(x) %||% seq_along(x)
}