-
Notifications
You must be signed in to change notification settings - Fork 4
/
subset.egor.R
330 lines (303 loc) · 10 KB
/
subset.egor.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
if (getRversion() >= "2.15.1")
utils::globalVariables(c(".altRow"))
#' Convert a table to a list of rows
#'
#' A convenience function converting a [data.frame()] or a [tibble()].
#'
#' @param x a [data.frame()], a [tibble()], or some other table data
#' structure backed by a [list()] of columns.
#'
#' @return A [list()] of length `nrow(x)`, with each element itself a
#' named [list()] containing the elements in the corresponding
#' row.
#'
#' @examples
#'
#' library(tibble)
#' (df <- tibble(x=2:1, y=list(list(1:3), list(3:4))))
#' rowlist(df)
#'
#' @export
rowlist <- function(x) {
apply(x, 1, identity)
}
#' Filter and Subset Ego-centered Datasets
#'
#' Functions to index and take subsets of [egor()] objects: manipulate
#' egos, alters, or alter-alter ties.
#'
#' @param x an [egor()] object.
#' @param unit a selector of the unit of analysis being affected: the
#' egos, the alters or the (alter-alter) ties. Note that only one
#' type of unit can be affected at a time. Defaults to the current
#' active unit selected by [activate.egor()].
#'
#' @param subset either an expression evaluated on each of the rows of
#' the selected unit (as in the eponymous argument of [subset()]) or
#' a function whose first argument is a row, specifying which egos,
#' alters, or alter-alter ties to keep. The expressions can access
#' variables in the calling environment; columns of the active unit,
#' columns of other units with which the active unit shares an ego
#' via `ego$`, `alter$`, and `aatie$` as well as the following
#' "virtual" columns to simplify indexing: \describe{
#'
#' \item{Ego index `.egoRow`}{ contains the index (counting from 1) of the row being
#' evaluated. (This can be used to access vector variables in the
#' calling environment.)}
#'
#' \item{Alter index `.altRow`}{ contains the index (counting from 1) of the row number in the alter table.}
#'
#' \item{Alter--alter indices `.srcRow` and `.tgtRow`}{ contain the
#' index (counting from 1) of the row of the alter being referenced by
#' `.srcID` and `.tgtID`. (This can be used to quickly access the
#' attributes of the alters in question.)}
#'
#' }
#'
#' @param ... extra arguments to `subset` if `subset` is a function; otherwise unused.
#'
#' @details
#'
#' Removing or duplicating an ego will also remove or duplicate their
#' alters and ties.
#'
#' @return An [egor()] object.
#'
#' @examples
#'
#' # Generate a small sample dataset
#' (e <- make_egor(5,4))
#'
#' # First three egos in the dataset
#' e[1:3,]
#'
#' # Using an external vector
#' # (though normally, we would use e[.keep,] here)
#' .keep <- rep(c(TRUE, FALSE), length.out=nrow(e$ego))
#' subset(e, .keep)
#'
#' # Filter egos
#' subset(x = egor32, subset = egor32$ego$variables$sex == "m", unit="ego")
#' subset(x = egor32, sex == "m")
#'
#' # Filter alters
#' subset(x = egor32, sex == "m", unit = "alter")
#'
#' # Filter aaties
#' subset(x = egor32, weight != 0, unit = "aatie")
#'
#' # Filter egos by alter variables (keep only egos that have more than 13 alters)
#' subset(x = egor32, nrow(alter) > 13, unit = "alter")
#'
#' # Filter alters by ego variables (keep only alters that have egos from Poland)
#' subset(x = egor32, ego$country == "Poland", unit = "ego")
#'
#' # Filter edges by alter variables (keep only edges between alters where `sex == "m"`)
#' subset(x = egor32, all(alter$sex == "m"), unit = "aatie")
#' @importFrom methods is
#' @importFrom dplyr nest_join
#' @export
subset.egor <- function(x, subset, ..., unit = attr(x, "active")) {
unit <- match.arg(unit, UNITS)
f <- try(is.function(subset), silent = TRUE)
if (is(f, "try-error") || !f) {
# Does the `if` ever not fire?
se <- substitute(subset)
pf <- parent.frame()
f <- function(r)
eval(se, r, pf)
} else
f <- subset
# The following works because we end up joining the same set of
# tables to any of these, except that for unit=="aatie", we also
# need to add row indices.
add_egoRow <- function(x) {
tmp <- as_tibble(x$ego)
tmp$.egoRow <- seq_len(nrow(x$ego))
tmp
}
add_altRow <- function(x) {
tmp <- x$alter
tmp$.altRow <-
stats::ave(logical(nrow(tmp)), tmp$.egoID, FUN = seq_along)
tmp
}
xa <- switch(
unit,
ego = add_egoRow(x),
alter =
# Within each ego, assign increasing alter
# indices. Note that the first argument of ave() is a
# dummy variable.
add_altRow(x),
aatie = {
alters_with_altRow <-
add_altRow(x) %>%
select(.egoID, .altID, .altRow)
xa <-
left_join(x$aatie,
alters_with_altRow,
by = c(".egoID", ".srcID" = ".altID")) %>%
rename(.srcRow = .altRow)
left_join(xa,
alters_with_altRow,
by = c(".egoID", ".tgtID" = ".altID")) %>%
rename(.tgtRow = .altRow)
}
)
# Join nested ego column
xa <-
nest_join(xa,
add_egoRow(x),
".egoID",
keep = TRUE,
name = "ego")
# Join nested alter column
by_alter <- switch(
unit,
ego = ".egoID",
alter = c(".egoID", ".altID"),
aatie = list(
c(".egoID", ".srcID" = ".altID"),
c(".egoID", ".tgtID" = ".altID")
)
)
xa <-
nest_join(xa,
add_altRow(x),
by_alter[[1]],
keep = TRUE,
name = "alter")
if (unit == "aatie") {
xa <-
nest_join(xa,
add_altRow(x),
by_alter[[2]],
keep = TRUE,
name = "alter2")
xa$alter <- purrr::map2(xa$alter, xa$alter2, bind_rows)
xa$alter2 <- NULL
}
# Join nested aatie column
by_aatie <- switch(
unit,
ego = list(".egoID", ".egoID"),
alter = list(
c(".egoID", ".altID" = ".srcID"),
c(".egoID", ".altID" = ".tgtID")
),
aatie = list(
c(".egoID", ".srcID" = ".srcID"),
c(".egoID", ".tgtID" = ".tgtID")
)
)
xa <-
nest_join(xa, x$aatie, by_aatie[[1]], keep = TRUE, name = "aatie")
if (unit != "ego") {
xa <-
nest_join(xa, x$aatie, by_aatie[[2]], keep = TRUE, name = "aatie2")
xa$aatie <- purrr::map2(xa$aatie, xa$aatie2, bind_rows)
xa$aatie2 <- NULL
}
# Call the function to perform indexing
i <- sapply(rowlist(xa), f, ..., simplify = TRUE)
# If `subset` is evaluated against the calling environment, we only need the lgl vector once:
if (is.matrix(i))
i <- i[, 1]
# Subset x by i
x[i, , unit = unit]
}
#' @rdname subset.egor
#'
#' @param i numeric or logical vector indexing the appropriate unit.
#'
#' @param j either an integer vector specifying which columns of the
#' filtered structure (ego, alters, or ties) to select, or a logical
#' vector specifying which columns to keep. Note that the special
#' columns .egoID, .altID, .srcID, .tgtID are not indexed by `j`.
# columns \Sexpr{sQuote(unlist(IDVARS))} are not indexed by `j`.
#'
#' @import tibble
#' @export
`[.egor` <- function(x, i, j, unit = attr(x, "active"), ...) {
unit <- match.arg(unit, UNITS)
if (missing(i))
i <- TRUE
if (missing(j))
j <- TRUE
switch(unit,
ego = {
eid <- as_tibble(x$ego)$.egoID
if (is.numeric(i) && any(duplicated(i))) {
warning(
"Some ego indices have been selected multiple times. They will be duplicated, and ",
sQuote(".egoID"),
"s renumbered to preserve uniqueness."
)
x$alter <-
map2(seq_along(i), alters_by_ego(x)[i], function(i, a) {
a[, ".egoID"] <- i
a
}) %>% bind_rows
if (!is.null(x$aatie))
x$aatie <-
map2(seq_along(i), aaties_by_ego(x)[i], function(i, aa) {
aa[, ".egoID"] <- i
aa
}) %>% bind_rows
# This guarantees that the ego ID column is always preserved.
x$ego <- x$ego[i, j, ...]
if (!".egoID" %in% names(as_tibble(x$ego))) {
if (has_ego_design(x))
x$ego$variables$.egoID <- eid[i]
else
x$ego$.egoID <- eid[i]
}
x$ego[, ".egoID"] <- seq_along(i)
} else{
# This guarantees that the ego ID column is always preserved.
x$ego <- x$ego[i, j, ...]
if (!".egoID" %in% names(as_tibble(x$ego))) {
if (has_ego_design(x))
x$ego$variables$.egoID <- eid[i]
else
x$ego$.egoID <- eid[i]
}
x$alter <-
filter(x$alter, .egoID %in% as_tibble(.env$x$ego)$.egoID)
x$aatie <-
filter(x$aatie, .egoID %in% as_tibble(.env$x$ego)$.egoID)
}
x
},
alter = {
if (!is.logical(i) && any(duplicated(i)))
stop("Indexing duplicated alters is not implemented at this time.")
eid <- x$alter$.egoID[i]
aid <- x$alter$.altID[i]
x$alter <- x$alter[i, j, ...]
if (!".egoID" %in% names(x$alter))
x$alter$.egoID <- eid
if (!".altID" %in% names(x$alter))
x$alter$.altID <- aid
# Explanation: keep a row in aaties iff its (egoID,altID) tuple can (still) be found in the alters as well.
trim_aaties(x)
},
aatie = {
if (!utils::hasName(x, "aatie"))
stop(
"Attempted indexing of alter-alter ties on an object with no alter-alter ties observed."
)
eid <- x$aatie$.egoID[i]
sid <- x$aatie$.srcID[i]
tid <- x$aatie$.srcID[i]
x$aatie <- x$aatie[i, j, ...]
if (!".egoID" %in% names(x$aatie))
x$aatie$.egoID <- eid
if (!".srcID" %in% names(x$aatie))
x$aatie$.srcID <- sid
if (!".tgtID" %in% names(x$aatie))
x$aatie$.tgtID <- tid
x
})
}