forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrouped-df.r
253 lines (200 loc) · 6.66 KB
/
grouped-df.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
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
#' A grouped data frame.
#'
#' The easiest way to create a grouped data frame is to call the \code{group_by}
#' method on a data frame or tbl: this will take care of capturing
#' the unevalated expressions for you.
#'
#' @keywords internal
#' @param data a tbl or data frame.
#' @param vars a list of quoted variables.
#' @param drop if \code{TRUE} preserve all factor levels, even those without
#' data.
#' @export
grouped_df <- function(data, vars, drop = TRUE) {
if (length(vars) == 0) {
return(tbl_df(data))
}
assert_that(is.data.frame(data), is.list(vars), all(sapply(vars,is.name)), is.flag(drop))
grouped_df_impl(data, unname(vars), drop)
}
#' @rdname grouped_df
#' @export
is.grouped_df <- function(x) inherits(x, "grouped_df")
#' @export
print.grouped_df <- function(x, ..., n = NULL, width = NULL) {
cat("Source: local data frame ", dim_desc(x), "\n", sep = "")
grps <- if (is.null(attr(x, "indices"))) "?" else length(attr(x, "indices"))
cat("Groups: ", commas(deparse_all(groups(x))), " [", big_mark(grps), "]\n", sep = "")
cat("\n")
print(trunc_mat(x, n = n, width = width), ...)
invisible(x)
}
#' @export
group_size.grouped_df <- function(x) {
group_size_grouped_cpp(x)
}
#' @export
n_groups.grouped_df <- function(x) {
length(attr(x, "indices"))
}
#' @export
groups.grouped_df <- function(x) {
attr(x, "vars")
}
#' @export
as.data.frame.grouped_df <- function(x, row.names = NULL,
optional = FALSE, ...) {
x <- ungroup(x)
class(x) <- "data.frame"
x
}
#' @export
ungroup.grouped_df <- function(x, ...) {
ungroup_grouped_df(x)
}
#' @export
`[.grouped_df` <- function(x, i, j, ...) {
y <- NextMethod()
group_vars <- vapply(groups(x), as.character, character(1))
if (!all(group_vars %in% names(y))) {
tbl_df(y)
} else {
grouped_df(y, groups(x))
}
}
#' @method rbind grouped_df
#' @export
rbind.grouped_df <- function(...) {
bind_rows(...)
}
#' @method cbind grouped_df
#' @export
cbind.grouped_df <- function(...) {
bind_cols(...)
}
# One-table verbs --------------------------------------------------------------
#' @export
select_.grouped_df <- function(.data, ..., .dots) {
dots <- lazyeval::all_dots(.dots, ...)
vars <- select_vars_(names(.data), dots)
vars <- ensure_grouped_vars(vars, .data)
select_impl(.data, vars)
}
ensure_grouped_vars <- function(vars, data, notify = TRUE) {
group_names <- vapply(groups(data), as.character, character(1))
missing <- setdiff(group_names, vars)
if (length(missing) > 0) {
if (notify) {
message("Adding missing grouping variables: ",
paste0("`", missing, "`", collapse = ", "))
}
vars <- c(stats::setNames(missing, missing), vars)
}
vars
}
#' @export
rename_.grouped_df <- function(.data, ..., .dots) {
dots <- lazyeval::all_dots(.dots, ...)
vars <- rename_vars_(names(.data), dots)
select_impl(.data, vars)
}
# Do ---------------------------------------------------------------------------
#' @export
do_.grouped_df <- function(.data, ..., env = parent.frame(), .dots) {
# Force computation of indices
if (is.null(attr(.data, "indices"))) {
.data <- grouped_df_impl(.data, attr(.data, "vars"),
attr(.data, "drop") %||% TRUE)
}
# Create ungroup version of data frame suitable for subsetting
group_data <- ungroup(.data)
args <- lazyeval::all_dots(.dots, ...)
named <- named_args(args)
env <- new.env(parent = lazyeval::common_env(args))
labels <- attr(.data, "labels")
index <- attr(.data, "indices")
n <- length(index)
m <- length(args)
# Special case for zero-group/zero-row input
if (n == 0) {
env$. <- group_data
if (!named) {
out <- eval(args[[1]]$expr, envir = env)[0, , drop = FALSE]
return(label_output_dataframe(labels, list(list(out)), groups(.data)))
} else {
out <- setNames(rep(list(list()), length(args)), names(args))
return(label_output_list(labels, out, groups(.data)))
}
}
# Create new environment, inheriting from parent, with an active binding
# for . that resolves to the current subset. `_i` is found in environment
# of this function because of usual scoping rules.
makeActiveBinding(env = env, ".", function(value) {
if (missing(value)) {
group_data[index[[`_i`]] + 1L, , drop = FALSE]
} else {
group_data[index[[`_i`]] + 1L, ] <<- value
}
})
out <- replicate(m, vector("list", n), simplify = FALSE)
names(out) <- names(args)
p <- progress_estimated(n * m, min_time = 2)
for (`_i` in seq_len(n)) {
for (j in seq_len(m)) {
out[[j]][`_i`] <- list(eval(args[[j]]$expr, envir = env))
p$tick()$print()
}
}
if (!named) {
label_output_dataframe(labels, out, groups(.data))
} else {
label_output_list(labels, out, groups(.data))
}
}
# Set operations ---------------------------------------------------------------
#' @export
distinct_.grouped_df <- function(.data, ..., .dots, .keep_all = FALSE) {
groups <- lazyeval::as.lazy_dots(groups(.data))
dist <- distinct_vars(.data, ..., .dots = c(.dots, groups),
.keep_all = .keep_all)
grouped_df(distinct_impl(dist$data, dist$vars, dist$keep), groups(.data))
}
# Random sampling --------------------------------------------------------------
#' @export
sample_n.grouped_df <- function(tbl, size, replace = FALSE, weight = NULL,
.env = parent.frame()) {
assert_that(is.numeric(size), length(size) == 1, size >= 0)
weight <- substitute(weight)
index <- attr(tbl, "indices")
sampled <- lapply(index, sample_group, frac = FALSE,
tbl = tbl, size = size, replace = replace, weight = weight, .env = .env)
idx <- unlist(sampled) + 1
grouped_df(tbl[idx, , drop = FALSE], vars = groups(tbl))
}
#' @export
sample_frac.grouped_df <- function(tbl, size = 1, replace = FALSE, weight = NULL,
.env = parent.frame()) {
assert_that(is.numeric(size), length(size) == 1, size >= 0)
if (size > 1 && !replace) {
stop("Sampled fraction can't be greater than one unless replace = TRUE",
call. = FALSE)
}
weight <- substitute(weight)
index <- attr(tbl, "indices")
sampled <- lapply(index, sample_group, frac = TRUE,
tbl = tbl, size = size, replace = replace, weight = weight, .env = .env)
idx <- unlist(sampled) + 1
grouped_df(tbl[idx, , drop = FALSE], vars = groups(tbl))
}
sample_group <- function(tbl, i, frac = FALSE, size, replace = TRUE,
weight = NULL, .env = parent.frame()) {
n <- length(i)
if (frac) size <- round(size * n)
check_size(size, n, replace)
# weight use standard evaluation in this function
if (!is.null(weight)) {
weight <- eval(weight, tbl[i + 1, , drop = FALSE], .env)
weight <- check_weight(weight, n)
}
i[sample.int(n, size, replace = replace, prob = weight)]
}