Skip to content

Commit

Permalink
ns_to_percents works on a data.frame with just one numeric col
Browse files Browse the repository at this point in the history
closes #89
  • Loading branch information
sfirke committed Mar 22, 2017
1 parent c79e6cb commit bf9b39f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
10 changes: 5 additions & 5 deletions R/ns_to_percents.R
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ ns_to_percents <- function(dat, denom = "row", na.rm = TRUE, total_n = NULL){


if(denom == "row"){
row_sum <- rowSums(dat[, numeric_cols], na.rm = na.rm)
dat[, numeric_cols] <- dat[, numeric_cols] / row_sum
row_sum <- rowSums(dat[numeric_cols], na.rm = na.rm)
dat[, numeric_cols] <- dat[numeric_cols] / row_sum
} else if(denom == "col"){
col_sum <- colSums(dat[, numeric_cols], na.rm = na.rm)
dat[, numeric_cols] <- sweep(dat[, numeric_cols], 2, col_sum,`/`) # from http://stackoverflow.com/questions/9447801/dividing-columns-by-colsums-in-r
col_sum <- colSums(dat[numeric_cols], na.rm = na.rm)
dat[, numeric_cols] <- sweep(dat[numeric_cols], 2, col_sum,`/`) # from http://stackoverflow.com/questions/9447801/dividing-columns-by-colsums-in-r
} else if(denom == "all"){
dat[, numeric_cols] <- dat[, numeric_cols] / complete_n
dat[numeric_cols] <- dat[numeric_cols] / complete_n
}

dat
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-ns-to-percents.R
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,13 @@ test_that("override value total_n functions correctly", {
cbind(data.frame(cyl = c(4, 6, 8)),
ns_to_percents(source1, denom = "all")[, -1] / 10) # divide by 10 because the mtcars n = 32
)
})

test_that("works with a single numeric column per #89", {
dat <- data.frame(Operation = c("Login", "Posted", "Deleted"), `Total Count` = c(5, 25, 40), check.names = FALSE)
expect_equal(dat %>% ns_to_percents("col"),
data.frame(Operation = c("Login", "Posted", "Deleted"),
`Total Count` = c(5/70, 25/70, 40/70),
check.names = FALSE)
)
})

0 comments on commit bf9b39f

Please sign in to comment.