Skip to content

Commit 7ac5b9b

Browse files
Always retain valid names in bind_rows(.id = ) (#7719)
* `.id` bug in `bind_rows()` * Update R/bind-rows.R Co-authored-by: Davis Vaughan <[email protected]> * Update tests/testthat/test-bind-rows.R Co-authored-by: Davis Vaughan <[email protected]> * update `NEWS.md` * grammar fix * Update tests/testthat/test-bind-rows.R Co-authored-by: Davis Vaughan <[email protected]> * Tweak NEWS * Remove `rlang::` --------- Co-authored-by: Davis Vaughan <[email protected]>
1 parent 2b75d1c commit 7ac5b9b

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# dplyr (development version)
22

3+
* `bind_rows()` now replaces empty (or `NA`) element names in a list with its numeric index while preserving existing names (#7719, @Meghansaha).
4+
35
* New `slice_sample()` example showing how to use it to shuffle rows (#7707, @Hzanib).
46

57
* Updated `across()` examples to include an example using `everything()` (#7621, @JBrandenburg02).

R/bind-rows.R

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,11 @@ bind_rows <- function(..., .id = NULL) {
6565
check_string(.id)
6666

6767
if (!is_named(dots)) {
68-
names(dots) <- seq_along(dots)
68+
# Replace `NA` or `""` names with their index,
69+
# but leave existing names in place (#7100)
70+
dots_with_names <- have_name(dots)
71+
dots_without_names <- which(!dots_with_names)
72+
names(dots)[dots_without_names] <- as.character(dots_without_names)
6973
}
7074
} else {
7175
# Don't let `vec_rbind(.id = NULL)` promote input names to row names

tests/testthat/test-bind-rows.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,16 @@ test_that("bind_rows() handles named list", {
145145
expect_equal(bind_rows(x), tibble(x = 1, y = 2, z = 3))
146146
})
147147

148+
test_that("bind_rows() handles empty names in a list (#7100)", {
149+
x <- rep(list(data.frame(x = 1)), times = 5)
150+
names(x) <- paste0("id_", 1:5)
151+
names(x)[c(3, 5)] <- NA_character_
152+
x <- bind_rows(x, .id = "id")
153+
154+
# If names are missing, bind_rows will replace with index
155+
expect_identical(x$id, c("id_1", "id_2", "3", "id_4", "5"))
156+
})
157+
148158
test_that("bind_rows() validates lists (#5417)", {
149159
out <- bind_rows(list(x = 1), list(x = 1, y = 1:2))
150160
expect_equal(out, tibble(x = c(1, 1, 1), y = c(NA, 1:2)))

0 commit comments

Comments
 (0)