【发布时间】:2015-03-08 15:29:20
【问题描述】:
我想计算一个平均值。这是带有示例数据的代码:
# sample data
Nr <- c(1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)
dph <- c(3.125000, 6.694737, 4.310680, 11.693735, 103.882353, 11.000000, 7.333333, 20.352941, 5.230769, NA, 4.615385, 47.555556, 2.941176, 18.956522, 44.320000, 28.500000, NA, 10.470588, 19.000000, 25.818182, 43.216783, 51.555556, 8.375000, 6.917647, 9.375000, 5.647059, 4.533333, 27.428571, 14.428571, NA, 1.600000, 5.764706, 4.705882, 55.272727, 2.117647, 30.888889, 41.222222, 23.444444, 2.428571, 6.200000, 17.076923, 21.280000, 40.829268, 14.500000, 6.250000, NA, 15.040000, 5.687204, 2.400000, NA, 26.375000, 18.064516, 4.000000, 6.139535, 8.470588, 128.666667, 2.235294, 34.181818, 116.000000, 6.000000, 5.777778, 10.666667, 15.428571, 54.823529, 81.315789, 42.333333)
dat <- data.frame(cbind(Nr = Nr, dph = dph))
# calculate mean directly
mean(dat$dph, na.rm = TRUE)
[1] 23.02403
# aggregate first, then calculate mean
mean(aggregate(dph ~ Nr, dat, mean, na.rm = T)$dph)
[1] 22.11743
# 23.02403 != 22.11743
为什么我会得到两个不同的结果?
问题解释:
我需要执行 Wilcoxon 测试,比较前基线和后基线。 Pre 是 3 个测量值,post 是 16 个。因为 Wilcoxon 测试需要两个相等长度的向量,所以我用aggregate 计算每个患者的 pre 和 post 均值,创建两个相等长度的向量。以上数据为pre。
编辑:
患者编号4 从数据中删除。但是使用Nr <- rep(1:22, 3) 会返回相同的结果。
【问题讨论】:
-
如果 Nr 包含 4 也会发生同样的情况吗?
-
@lawyeR 是的。 (我尝试使用
Nr <- rep(1:22, 3)。)只是为了解释一下:4 号患者已从数据中删除。 -
没有理由你应该得到相同的结果。例如:
Nr<-c(1, 1, 2, 2)和dph<-c(1, 2, 3, NA),您应该意识到如何获得不同的值。请记住,总体而言,全局平均值不同于“平均值的平均值”。 -
参见例如here