我有两组值,如下所示:
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
对于y它将是 (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
我希望有某种方法可以使代码更简单。
答案 0 :(得分:1)
一种可能是:
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