Skip to content

Commit e3610fd

Browse files
committed
fix: add input check to merge_start_stop() to ensure unique rows in all supplied datasets
1 parent 111a9b8 commit e3610fd

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

NAMESPACE

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,5 @@ importFrom(data.table,setkey)
4343
importFrom(data.table,setkeyv)
4444
importFrom(data.table,setnames)
4545
importFrom(data.table,shift)
46+
importFrom(data.table,uniqueN)
4647
importFrom(fastmatch,"%fin%")

R/merge_start_stop.r

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#' @importFrom data.table :=
1212
#' @importFrom data.table rbindlist
1313
#' @importFrom data.table shift
14+
#' @importFrom data.table uniqueN
1415
#' @export
1516
merge_start_stop <- function(x, y, ..., dlist, by, start="start",
1617
stop="stop", all=FALSE, all.x=all, all.y=all,
@@ -58,7 +59,7 @@ merge_start_stop <- function(x, y, ..., dlist, by, start="start",
5859
if (!all(unlist(type_value_i) %in% c("logical", "numeric", "character",
5960
"integer"))) {
6061
stop("All columns containing variables (columns except 'by', 'start' ",
61-
"and 'stop') must be of type:\n 'logical', 'numeric' or ",
62+
"and 'stop') must be of type:\n 'logical', 'numeric', 'integer' or ",
6263
"'character'.", call.=FALSE)
6364
}
6465

@@ -74,6 +75,12 @@ merge_start_stop <- function(x, y, ..., dlist, by, start="start",
7475
variable.factor=FALSE)
7576
)
7677
}
78+
79+
# check if all values in a dataset are unique
80+
if (uniqueN(dlist[[i]]) != nrow(dlist[[i]])) {
81+
stop("Duplicate rows found in dataset ", i, ". Remove duplicates",
82+
" and re-run the function.", call.=FALSE)
83+
}
7784
}
7885

7986
# put together all datasets in one

tests/testthat/test_merge_start_stop.r

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,3 +601,21 @@ test_that("general test cases, 2 datasets, integers", {
601601
output <- merge_start_stop(dlist=dlist, by="ID", center_on_first=TRUE)
602602
expect_true(all(output[, .(start = min(start)), by=ID]$start==0))
603603
})
604+
605+
test_that("error with duplicate rows", {
606+
607+
d1 <- data.table(ID=c(1, 1, 1, 1, 2, 2, 3, 5),
608+
start=c(20, 210, 370, 370, 55, 98, 1, 9),
609+
stop=c(189, 301, 375, 375, 90, 190, 900, 10),
610+
d1=c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE))
611+
612+
d2 <- data.table(ID=c(1, 1, 1, 2, 2, 3, 5),
613+
start=c(17, 211, 370, 58, 98, 1, 9),
614+
stop=c(189, 321, 375, 90, 191, 94, 11),
615+
d2=c(TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE))
616+
dlist <- list(d1, d2)
617+
618+
expect_error({merge_start_stop(d1, d2, by="ID")},
619+
paste0("Duplicate rows found in dataset 1. Remove ",
620+
"duplicates and re-run the function."))
621+
})

0 commit comments

Comments
 (0)