获得两组分数的平均值的绝对偏差 [英] Obtaining absolute deviation from mean for two sets of scores
问题描述
为了获得两组分数的平均值的绝对偏差,我通常需要在 R 中编写长代码,如下所示.
To obtain absolute deviation from the mean for two groups of scores, I usually need to write long codes in R such as the ones shown below.
我想知道是否有可能在 BASE R 中以某种方式 Vectorize
mad()
函数,以便每组分数的平均分数的绝对偏差在我下面展示的示例中,可以使用 mad()
的 Vectorized
版本获得?任何其他可行的想法都受到高度赞赏?
I was wondering if it might be possible in BASE R to somehow Vectorize
the mad()
function so that the absolute deviation from the mean scores for each group of scores in the example I'm showing below could be obtained using that Vectorized
version of mad()
? Any other workable ideas are highly appreciated?
set.seed(0)
y = as.vector(unlist(mapply(FUN = rnorm, n = c(10, 10)))) # Produces two sets of scores
groups = factor( rep(1:2, times = c(10, 10) ) ) # Grouping ID variable
G1 = y[groups == 1] # subset y scores for group 1
G2 = y[groups == 2] # subset y scores for group 2
G1.abs.dev = abs(G1 - mean(G1)) # absolute deviation from mean scores for group 1
G2.abs.dev = abs(G2 - mean(G2)) # absolute deviation from mean scores for group 2
推荐答案
怎么样
score <- lapply(split(y, groups), FUN = function (u) abs(u - mean(u)))
或
score <- ave(y, groups, FUN = function (u) abs(u - mean(u)))
结果的组织方式不同.选择最适合您的那一款.
The results are organized in a different way. Choose the one that is most comfortable to you.
你的措辞有问题.mad
返回数据的单个统计信息/值.例如,
There is something wrong with your wording. mad
returns a single statistic / value for data. For example,
sapply(split(y, groups), mad)
您不是对 mad
进行矢量化,而是简单地计算每个数据的偏差,如示例代码所示.
You are not vectorizing mad
, but simply computing the deviation for each datum as your example code shows.
这篇关于获得两组分数的平均值的绝对偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!