diff --git a/NEWS.md b/NEWS.md index ae06113..ab256f2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -6,6 +6,9 @@ - New function `isid` for determining if a combination of variables uniquely define the rows in a dataframe + +### Bug Fixes +- Fixed error in `statamode` with `method = "last"` thanks to PR from @larcat - Fix import compatibility with ggplot2 ## eeptools 1.1.1 diff --git a/R/statamode.R b/R/statamode.R index 82a1cf8..bc2076f 100644 --- a/R/statamode.R +++ b/R/statamode.R @@ -81,27 +81,21 @@ statamode <- function(x, method = c("last", "stata", "sample")){ } } else if (method=='last'){ - z <- table(as.vector(x)) - m <- names(z)[z == max(z)] - if (length(m) == 1){ + x_vec <- as.vector(x) + z <- table(x_vec) + m <- names(z[which(z == max(z))]) + m <- x[which(x %in% m)] + m <- m[length(m)] + if(length(m) > 0){ if(xClass == "factor"){ m <- factor(m) - } else{ + return(m) + } else { class(m) <- xClass + return(m) } - return(m) } - else if (length(m) > 1){ - m <- max(x[match(x, m) == max(match(x,m), na.rm=TRUE)], - na.rm=TRUE) - if(xClass == "factor"){ - m <- factor(m) - } else{ - class(m) <- xClass - } - return(tail(m, 1)) - } - else if (length(m) < 1){ + else if(length(m) < 1){ if(xClass == "character"){ return(NA_character_) } else if(xClass == "numeric"){ @@ -113,4 +107,4 @@ statamode <- function(x, method = c("last", "stata", "sample")){ } } } -} +} \ No newline at end of file diff --git a/tests/testthat/test-statamode.r b/tests/testthat/test-statamode.r index a13df6b..3c1f712 100644 --- a/tests/testthat/test-statamode.r +++ b/tests/testthat/test-statamode.r @@ -1,10 +1,11 @@ context("Correct mode selected") test_that("statamode selects the mode right for each method", { - expect_match(statamode("a"), "a") - expect_match(statamode(c("a", "a", "b", "b"), method="stata"), ".") - expect_match(statamode(c("a", "a", "b", "b"), method="last"), "b") - # expect_match(statamode(c("a", "a", "b", "b"), method="sample"), c("a", "b"), all=FALSE) + expect_that(statamode("a"), matches("a")) + expect_that(statamode(c("a", "a", "b", "b"), method="stata"), matches(".")) + expect_that(statamode(c("a", "a", "b", "b"), method="last"), matches("b")) + expect_that(statamode(c("b", "b", "a", "a"), method="last"), matches("a")) + # expect_that(statamode(c("a", "a", "b", "b"), method="sample"), matches(c("a", "b"),all=FALSE)) }) set.seed(100) @@ -133,5 +134,4 @@ test_that("statamode handles all types of modes", { } } } -}) - +}) \ No newline at end of file