What seems like a straightforward calculation of group means and standard errors doesn’t work and I can’t figure out why. I get NA
for the std. errors
data("AddHealth", package = "heplots")
library(dplyr)
# use a function
std.error <- function(x, na.rm = TRUE) {
sd(x, na.rm = na.rm) / sqrt(length(x))
}
# try it two ways
AddHealth |>
group_by(grade) |>
summarise(depression = mean(depression),
anxiety = mean(anxiety),
n = n(),
se.dep = std.error(depression),
se.anx = sd(anxiety, na.rm = TRUE) / sqrt(n)) |>
print()
I get NA
for the standard error whether I use my function or do the calculation directly.
This should be relatively simple. Why doesn’t this work? How can I get what I want?
# A tibble: 6 × 6
grade depression anxiety n se.dep se.anx
<ord> <dbl> <dbl> <int> <dbl> <dbl>
1 7 0.881 0.751 622 NA NA
2 8 1.08 0.804 664 NA NA
3 9 1.17 0.934 778 NA NA
4 10 1.27 0.956 817 NA NA
5 11 1.37 1.12 790 NA NA
6 12 1.34 1.10 673 NA NA