Skip to content

Commit

Permalink
Clean stop_on_differing_names()
Browse files Browse the repository at this point in the history
  • Loading branch information
hsonne committed Jan 6, 2024
1 parent 8a8f8a9 commit 95bc422
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
24 changes: 14 additions & 10 deletions R/import_rawdata.R
Original file line number Diff line number Diff line change
Expand Up @@ -81,25 +81,29 @@ stop_on_differing_names <- function(x)
stopifnot(is.list(x), all(sapply(x, is.data.frame)))

# Return if there are not at least two data frames
if (length(x) < 2) {

if (length(x) < 2L) {
return()
}

# Get the column names of the first data frame of the list
names_1 <- names(x[[1]])
columns_of_first <- names(x[[1L]])

# Names of data frames in list x
df_names <- names(x)
is_empty <- df_names == ""
df_names[is_empty] <- sprintf("<unnamed_%d>", which(is_empty))

# Compare with the column names of the other data frames
for (i in seq_along(x)[-1]) {
for (i in seq_along(df_names)[-1L]) {

names_i <- names(x[[i]])
columns_of_current <- names(x[[i]])

if (! identical(names_1, names_i)) {

if (!identical(columns_of_first, columns_of_current)) {
pasted <- function(x) paste(x, collapse = ", ")
stop_(
"There are differing column names:\n",
" ", names(x)[1], ": ", paste(names_1, collapse = ", "),
"\n ", names(x)[i], ": ", paste(names_i, collapse = ", ")
"There are differing column names:",
"\n ", df_names[1L], ": ", pasted(columns_of_first),
"\n ", df_names[i], ": ", pasted(columns_of_current)
)
}
}
Expand Down
25 changes: 14 additions & 11 deletions tests/testthat/test-function-stop_on_differing_names.R
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
#
# This test file has been generated by kwb.test::create_test_files()
# launched by user mrustl on 2022-11-18 13:49:45.
# Your are strongly encouraged to modify the dummy functions
# so that real cases are tested. You should then delete this comment.
#
#library(testthat)

test_that("stop_on_differing_names() works", {

expect_error(
kwb.umberto:::stop_on_differing_names()
# argument "x" is missing, with no default
)
f <- kwb.umberto:::stop_on_differing_names

expect_error(f())

dfs <- list(
df1 = data.frame(a = 1, b = 2),
df2 = data.frame(a = 1, b = 2, c = 3),
data.frame(a = 2, b = 3)
)

expect_error(f(dfs))
expect_error(f(dfs[-1L]), "<unnamed_2>")

expect_silent(f(dfs[-2L]))
})

0 comments on commit 95bc422

Please sign in to comment.