Debian Codegraph @

R/bind.R

raw
1
2 bind <- function(data, names = NULL, index = "Index") {
3
4 # keep only non-empty data
5 data <- Filter(NROW, data)
6 if (!length(data))
7 return(NULL)
8
9 # check for quick exit
10 if (length(data) == 1L) {
11
12 # no-name case
13 if (is.null(names(data))) {
14 rhs <- data[[1L]]
15 names(rhs) <- names(rhs) %||% names
16 return(as_data_frame(rhs))
17 }
18
19 # named case
20 lhs <- list(rep.int(names(data), times = NROW(data[[1L]])))
21 names(lhs) <- index
22 rhs <- as.list(data[[1L]])
23 return(as_data_frame(c(lhs, rhs)))
24
25 }
26
27 # ensure all datasets have the same column names
28 # try to preserve the ordering of names if possible
29 # (try to find one dataset which has all column relevant column names)
30 nms <- character()
31 for (i in seq_along(data)) {
32 names(data[[i]]) <- names(data[[i]]) %||% names
33 nmsi <- names(data[[i]])
34 if (length(nmsi) > length(nms))
35 nms <- nmsi
36 }
37
38 # check now if we've caught all relevant names; if we didn't,
39 # just fall back to a "dumb" union
40 allnms <- unique.default(unlist(lapply(data, names), use.names = FALSE))
41 if (!setequal(nms, allnms))
42 nms <- allnms
43
44 # we've collected all names; now fill with NAs as necessary
45 filled <- map(data, function(datum) {
46 datum[setdiff(nms, names(datum))] <- NA
47 datum[nms]
48 })
49
50 # we've collected and ordered each data.frame, now merge them
51 rhs <- .mapply(c, filled, list(use.names = FALSE))
52 names(rhs) <- names(filled[[1L]])
53
54 if (is.null(names(data))) {
55 names(rhs) <- names(rhs) %||% names
56 return(as_data_frame(rhs))
57 }
58
59 if (index %in% names(rhs)) {
60 fmt <- "name collision: bound list already contains column called '%s'"
61 stopf(fmt, index)
62 }
63
64 lhs <- list()
65 rows <- function(item) nrow(item) %||% length(item[[1L]])
66 lhs[[index]] <- rep.int(names(filled), times = map_dbl(filled, rows))
67
68 as_data_frame(c(lhs, rhs))
69
70 }
71
72
73
74
75