计算组内和组间的平均差异
Calculate the mean difference within and between groups
我有两组值如下:
x <- as.vector(c(1, 2, 3, 2, 1))
y <- as.vector(c(7, 7, 8, 9, 9))
我正在尝试计算每组值的平均差以及组间值的平均差。
在这个小例子中,对于 x,平均差为
(1+2+1+0+1+0+1+1+2+1)/10=10/10=1
对你来说是
(0+1+2+2+1+2+2+1+1+0)/10=12/10=1.2
组之间,应该是
(6+6+7+8+8+5+5+6+7+7+4+4+5+6+6+5+5+6+7+7+6+6+7+8+8 )/25=155/25=6.2
我希望有一些方法可以用更简单的代码来做到这一点。
一种可能是:
xy_diff <- abs(sapply(x, "-", y))
sum(xy_diff)/(dim(xy_diff)[1]*dim(xy_diff)[2])
[1] 6.2
x_diff <- abs(sapply(x, "-", x))
x_diff <- x_diff[upper.tri(x_diff)]
sum(x_diff/length(x_diff))
[1] 1
y_diff <- abs(sapply(y, "-", y))
y_diff <- y_diff[upper.tri(y_diff)]
sum(y_diff/length(y_diff))
[1] 1.2
我有两组值如下:
x <- as.vector(c(1, 2, 3, 2, 1))
y <- as.vector(c(7, 7, 8, 9, 9))
我正在尝试计算每组值的平均差以及组间值的平均差。
在这个小例子中,对于 x,平均差为 (1+2+1+0+1+0+1+1+2+1)/10=10/10=1
对你来说是 (0+1+2+2+1+2+2+1+1+0)/10=12/10=1.2
组之间,应该是 (6+6+7+8+8+5+5+6+7+7+4+4+5+6+6+5+5+6+7+7+6+6+7+8+8 )/25=155/25=6.2
我希望有一些方法可以用更简单的代码来做到这一点。
一种可能是:
xy_diff <- abs(sapply(x, "-", y))
sum(xy_diff)/(dim(xy_diff)[1]*dim(xy_diff)[2])
[1] 6.2
x_diff <- abs(sapply(x, "-", x))
x_diff <- x_diff[upper.tri(x_diff)]
sum(x_diff/length(x_diff))
[1] 1
y_diff <- abs(sapply(y, "-", y))
y_diff <- y_diff[upper.tri(y_diff)]
sum(y_diff/length(y_diff))
[1] 1.2