-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfill_na.R
69 lines (64 loc) · 1.57 KB
/
fill_na.R
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
#' Fill NA with the last no-NA value generic.
#'
#' This method can apply to numeric vector, data.frame/tibble. grouped_df.
#' If you want to apply to data.frame/tibble, please \code{library(dplyr)}.
#'
#' @param x a data.frame or a vector
#' @param ... col names character vector or just bare name.
#'
#' @return data.frame or a vector
#'
#' @examples
#' x <- c(1, NA, NA, 2, 3)
#' y <- c(NA, NA, 1, NA, 3)
#' xy <- data.frame(x,y)
#' fill_na(x)
#' fill_na(y)
#' \dontrun{
#' # require(dplyr)
#' fill_na(xy, x, y)
#' fill_na(xy, c("x","y"))
#' fill_na(xy, starts_with("x"))
#' }
#' @seealso \code{\link[tidyr]{fill}} \code{\link[dplyr]{group_by}}
#'
#' @export
fill_na <- function(x, ...) {
UseMethod("fill_na")
}
#' @inheritParams fill_na
#' @export
#' @rdname fill_na
fill_na.default <- function(x, ...) {
stopifnot(is.vector(x))
a <- !is.na(x)
x[which(a)[c(1, seq_along(which(a)))][cumsum(a) + 1]]
}
#' @inheritParams fill_na
#' @export
#' @rdname fill_na
fill_na.tbl_df <- function(x, ...) {
if (requireNamespace("dplyr", quietly = TRUE)) {
fill_cols <- unname(tidyselect::vars_select(names(x), ...))
for (col in fill_cols) {
x[[col]] <- fill_na(x[[col]])
}
x
} else {
print("please library(dplyr) ")
}
}
#' @inheritParams fill_na
#' @export
#' @rdname fill_na
fill_na.data.frame <- function(x, ...) {
if (requireNamespace("tidyselect", quietly = TRUE)) {
fill_cols <- unname(tidyselect::vars_select(names(x), ...))
for (col in fill_cols) {
x[[col]] <- fill_na(x[[col]])
}
x
} else {
print("please library(tidyselect) ")
}
}