diff --git a/R/bidsio.R b/R/bidsio.R index df35627..cf97b28 100644 --- a/R/bidsio.R +++ b/R/bidsio.R @@ -358,6 +358,14 @@ read_confounds.bids_project <- function(x, subid=".*", task=".*", session=".*", if (!inherits(x, "bids_project")) { stop("`x` must be a `bids_project` object.") } + + if (!is.numeric(npcs) || length(npcs) != 1 || npcs < 0 || npcs != as.integer(npcs)) { + stop("`npcs` must be a non-negative integer.") + } + + if (!is.numeric(perc_var) || length(perc_var) != 1 || perc_var < 0 || perc_var > 100) { + stop("`perc_var` must be between 0 and 100.") + } # Check participants sids <- participants(x) @@ -446,6 +454,13 @@ read_confounds.bids_project <- function(x, subid=".*", task=".*", session=".*", #' @keywords internal process_confounds <- function(dfx, center=TRUE, scale=TRUE, npcs=-1, perc_var=-1) { + if (!is.numeric(npcs) || length(npcs) != 1 || npcs < 0 || npcs != as.integer(npcs)) { + stop("`npcs` must be a non-negative integer.") + } + + if (!is.numeric(perc_var) || length(perc_var) != 1 || perc_var < 0 || perc_var > 100) { + stop("`perc_var` must be between 0 and 100.") + } m <- as.matrix(dfx) # Impute NAs if (anyNA(m)) { diff --git a/tests/testthat/test_read_confounds.R b/tests/testthat/test_read_confounds.R index 9e66cc4..0bbdfb7 100644 --- a/tests/testthat/test_read_confounds.R +++ b/tests/testthat/test_read_confounds.R @@ -72,3 +72,12 @@ test_that("canonical names resolve to dataset columns", { cols <- names(conf$data[[1]]) expect_true(all(c("CSF", "WhiteMatter", "FramewiseDisplacement", "GlobalSignal") %in% cols)) }) + +test_that("invalid PCA parameters trigger errors", { + setup <- create_confounds_proj() + on.exit(unlink(setup$path, recursive = TRUE, force = TRUE), add = TRUE) + expect_error(read_confounds(setup$proj, npcs = -1), "npcs") + expect_error(read_confounds(setup$proj, npcs = 1.5), "npcs") + expect_error(read_confounds(setup$proj, perc_var = -10), "perc_var") + expect_error(read_confounds(setup$proj, perc_var = 110), "perc_var") +})