Skip to content

Commit 758bc59

Browse files
authored
don't drop ordering from ordinal factors (#3710)
1 parent 89120e8 commit 758bc59

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

R/compat-plyr.R

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,15 +273,22 @@ rbind_dfs <- function(dfs) {
273273
allocated <- rep(FALSE, length(columns))
274274
names(allocated) <- columns
275275
col_levels <- list()
276+
ord_levels <- list()
276277
for (df in dfs) {
277278
new_columns <- intersect(names(df), columns[!allocated])
278279
for (col in new_columns) {
279280
if (is.factor(df[[col]])) {
281+
all_ordered <- all(vapply(dfs, function(df) {
282+
val <- .subset2(df, col)
283+
is.null(val) || is.ordered(val)
284+
}, logical(1)))
280285
all_factors <- all(vapply(dfs, function(df) {
281286
val <- .subset2(df, col)
282287
is.null(val) || is.factor(val)
283288
}, logical(1)))
284-
if (all_factors) {
289+
if (all_ordered) {
290+
ord_levels[[col]] <- unique(unlist(lapply(dfs, function(df) levels(.subset2(df, col)))))
291+
} else if (all_factors) {
285292
col_levels[[col]] <- unique(unlist(lapply(dfs, function(df) levels(.subset2(df, col)))))
286293
}
287294
out[[col]] <- rep(NA_character_, total)
@@ -318,6 +325,9 @@ rbind_dfs <- function(dfs) {
318325
}
319326
}
320327
}
328+
for (col in names(ord_levels)) {
329+
out[[col]] <- ordered(out[[col]], levels = ord_levels[[col]])
330+
}
321331
for (col in names(col_levels)) {
322332
out[[col]] <- factor(out[[col]], levels = col_levels[[col]])
323333
}

tests/testthat/test-rbind-dfs.R

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
context("data.frame binding")
2+
3+
test_that("rbind_dfs keep classes of columns", {
4+
df <- data_frame(
5+
integer = seq_len(10),
6+
numeric = as.numeric(seq_len(10)),
7+
character = letters[1:10],
8+
factor = factor(letters[1:10]),
9+
ordered = ordered(letters[1:10]),
10+
date = Sys.Date()
11+
)
12+
df2 <- rbind_dfs(list(df[1:5, ], df[6:10, ]))
13+
expect_equal(df2, df)
14+
})

0 commit comments

Comments
 (0)