I need to generate reports for different groups and compute mean values for different subgroups. However, the number of cases it very small, so that t.test() throws an error.
Here's an example:
library(tidyverse)
n <- 10
test_df <- data.frame(var = sample(1:5, size=n, replace=TRUE),
grp = sample(c("A", "B", "C"), size = n, replace=TRUE))
# Throws an error when the numbers are too small:
#
# test_df %>%
# group_by(grp) %>%
# summarise(mean = mean(var, na.rm=TRUE),
# n = n(),
# uci = t.test(var, conf.level = .95)$conf.int[[2]],
# lci = t.test(var, conf.level = .95)$conf.int[[1]])
# Try to avoid the error by checking for sd(var) == 0
test_df %>%
group_by(grp) %>%
summarise(mean = mean(var, na.rm=TRUE),
n = n(),
uci = if(sd(var) == 0) NA else t.test(var, conf.level = .95)$conf.int[[2]],
lci = if(sd(var) == 0) NA else t.test(var, conf.level = .95)$conf.int[[1]])
I was trying to check for sd(var) == 0
in order to prevent the error to occur. However this does not solve the problem completely (if you execute the code many times it will still throw an error). What conditions do I have to check for?