-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsmartbind.R
311 lines (281 loc) · 8.98 KB
/
smartbind.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
#' Efficient rbind of data frames, even if the column names don't match
#'
#' Efficient rbind of data frames, even if the column names don't match
#'
#'
#' @param \dots Data frames to combine
#' @param list List containing data frames to combine
#' @param fill Value to use when 'filling' missing columns. Defaults to
#' \code{NA}.
#' @param sep Character string used to separate column names when pasting them
#' together.
#' @param verbose Logical flag indicating whether to display processing
#' messages. Defaults to \code{FALSE}.
#' @return The returned data frame will contain: \item{columns}{all columns
#' present in any provided data frame} \item{rows}{a set of rows from each
#' provided data frame, with values in columns not present in the given data
#' frame filled with missing (\code{NA}) values.} The data type of columns will
#' be preserved, as long as all data frames with a given column name agree on
#' the data type of that column. If the data frames disagree, the column will
#' be converted into a character strings. The user will need to coerce such
#' character columns into an appropriate type.
#' @author Gregory R. Warnes \email{greg@@warnes.net}
#' @seealso \code{\link{rbind}}, \code{\link{cbind}}
#' @keywords manip
#' @examples
#'
#'
#' df1 <- data.frame(A = 1:10, B = LETTERS[1:10], C = rnorm(10))
#' df2 <- data.frame(A = 11:20, D = rnorm(10), E = letters[1:10])
#'
#' # rbind would fail
#' \dontrun{
#' rbind(df1, df2)
#' # Error in match.names(clabs, names(xi)) : names do not match previous
#' # names:
#' # D, E
#' }
#' # but smartbind combines them, appropriately creating NA entries
#' smartbind(df1, df2)
#'
#' # specify fill=0 to put 0 into the missing row entries
#' smartbind(df1, df2, fill = 0)
#' \dontshow{
#' n <- 10 # number of data frames to create
#' s <- 10 # number of rows in each data frame
#'
#' # create a bunch of column names
#' names <- LETTERS[2:5]
#'
#' # create a list 'Z' containing 'n' data frames, each with 3 columns
#' # and 's' rows. The first column is always named 'A', but the other
#' # two have a names randomly selected from 'names'
#'
#' Z <- list()
#' for (i in 1:n)
#' {
#' X <- data.frame(
#' A = sample(letters, s, replace = TRUE),
#' B = letters[1:s],
#' C = rnorm(s)
#' )
#' colnames(X) <- c("A", sample(names, 2, replace = FALSE))
#' Z[[i]] <- X
#' }
#'
#' # Error in match.names(clabs, names(xi)) : names do not match
#' # previous names: E
#'
#' # But smartbind will 'do the right thing'
#' df <- do.call("smartbind", Z)
#' df
#'
#' # Equivalent call:
#' df <- smartbind(list = Z)
#' }
#'
#' @importFrom utils modifyList
#' @export
smartbind <- function(..., list, fill = NA, sep = ":", verbose = FALSE) {
data <- base::list(...)
if (!missing(list)) {
data <- modifyList(list, data)
}
data <- data[!sapply(data, function(l) is.null(l) | (ncol(l) == 0) | (nrow(l) == 0))]
defaultNames <- seq.int(length(data))
if (is.null(names(data))) {
names(data) <- defaultNames
}
emptyNames <- names(data) == ""
if (any(emptyNames)) {
names(data)[emptyNames] <- defaultNames[emptyNames]
}
data <- lapply(
data,
function(x) {
if (is.matrix(x) || is.data.frame(x)) {
x
} else {
data.frame(as.list(x), check.names = FALSE)
}
}
)
# retval <- new.env()
retval <- base::list()
rowLens <- unlist(lapply(data, nrow))
nrows <- sum(rowLens)
rowNameList <- unlist(lapply(
names(data),
function(x) {
if (rowLens[x] <= 1) {
x
} else {
paste(x, seq(1, rowLens[x]), sep = sep)
}
}
))
colClassList <- vector(mode = "list", length = length(data))
factorColumnList <- vector(mode = "list", length = length(data))
factorLevelList <- vector(mode = "list", length = length(data))
start <- 1
blockIndex <- 1
for (block in data)
{
colClassList[[blockIndex]] <- base::list()
factorColumnList[[blockIndex]] <- character(length = 0)
factorLevelList[[blockIndex]] <- base::list()
if (verbose) print(head(block))
end <- start + nrow(block) - 1
for (col in colnames(block))
{
classVec <- class(block[, col])
## store class and factor level information for later use
colClassList[[blockIndex]][[col]] <- classVec
if ("factor" %in% classVec) {
factorColumnList[[blockIndex]] <-
c(factorColumnList[[blockIndex]], col)
factorLevelList[[blockIndex]][[col]] <-
levels(block[, col])
}
if (verbose) {
cat("Start:", start,
" End:", end,
" Column:", col,
"\n",
sep = ""
)
}
if ("factor" %in% classVec) {
newclass <- "character"
}
else {
newclass <- classVec[1]
}
## Coerce everything that isn't a native type to character
if (!(newclass %in% c(
"logical", "integer", "numeric",
"complex", "character", "raw"
))) {
newclass <- "character"
warning(
"Converting non-atomic type column '", col,
"' to type character."
)
}
if (!(col %in% names(retval))) {
retval[[col]] <- as.vector(rep(fill, nrows), mode = newclass)
}
## Handle case when current and previous native types differ
oldclass <- class(retval[[col]])
if (oldclass != newclass) {
# handle conversions in case of conflicts
# numeric vs integer --> numeric
# complex vs numeric or integer --> complex
# anything else: --> character
if (oldclass %in% c("integer", "numeric") && newclass %in% c("integer", "numeric")) {
class(retval[[col]]) <- mode <- "numeric"
} else if (oldclass == "complex" && newclass %in% c("integer", "numeric")) {
class(retval[[col]]) <- mode <- "complex"
} else if (oldclass %in% c("integer", "numeric") && newclass == "complex") {
class(retval[[col]]) <- mode <- "complex"
} else {
class(retval[[col]]) <- mode <- "character"
warning(
"Column class mismatch for '", col, "'. ",
"Converting column to class 'character'."
)
}
}
else {
mode <- oldclass
}
if (mode == "character") {
vals <- as.character(block[, col])
} else {
vals <- block[, col]
}
retval[[col]][start:end] <- as.vector(vals, mode = mode)
}
start <- end + 1
blockIndex <- blockIndex + 1
}
all.equal.or.null <- function(x, y) {
if (is.null(x) || is.null(y)) {
return(TRUE)
} else {
return(all.equal(x, y))
}
}
## Handle factors, merging levels
for (col in unique(unlist(factorColumnList)))
{
## Ensure column classes match across blocks
colClasses <- lapply(colClassList, function(x) x[[col]])
firstNotNull <- which(!sapply(colClasses, is.null))[1]
allSameOrNull <- all(sapply(
colClasses[-firstNotNull],
function(x) isTRUE(all.equal.or.null(colClasses[[firstNotNull]], x))
))
if (allSameOrNull) {
# grab the first *non-NULL* class information
colClass <- colClasses[[firstNotNull]]
}
else {
warning(
"Column class mismatch for '", col, "'. ",
"Converting column to class 'character'."
)
next()
}
## check if factor levels are all the same
colLevels <- lapply(factorLevelList, function(x) x[[col]])
firstNotNull <- which(!sapply(colLevels, is.null))[1]
allSameOrNull <- all(sapply(
colLevels[-firstNotNull],
function(x) isTRUE(all.equal.or.null(colLevels[[firstNotNull]], x))
))
if (allSameOrNull) {
if ("ordered" %in% colClass) {
retval[[col]] <- ordered(retval[[col]], levels = colLevels[[firstNotNull]])
} else {
retval[[col]] <- factor(retval[[col]], levels = colLevels[[firstNotNull]])
}
}
else {
## Check if longest set of levels is a superset of all others,
## and use that one
longestIndex <- which.max(sapply(colLevels, length))
longestLevels <- colLevels[[longestIndex]]
allSubset <- all(sapply(
colLevels[-longestIndex],
function(l) all(l %in% longestLevels)
))
if (allSubset) {
if ("ordered" %in% colClass) {
retval[[col]] <- ordered(retval[[col]], levels = longestLevels)
} else {
retval[[col]] <- factor(retval[[col]], levels = longestLevels)
}
}
else {
# form superset by appending to longest level set
levelSuperSet <- unique(c(longestLevels, unlist(colLevels)))
retval[[col]] <- factor(retval[[col]], levels = levelSuperSet)
if (length(colClass) > 1) # not just plain factor
{
warning(
"column '", col, "' of class ",
paste("'", colClass, "'",
collapse = ":",
sep = "'"
),
" converted to class 'factor'. Check level ordering."
)
}
}
}
}
attr(retval, "row.names") <- rowNameList
class(retval) <- "data.frame"
return(retval)
}