首页 > 解决方案 > 如何计算 x=1 时 y 的平均值

问题描述

我正在尝试找出集群的平均值,我使用cluster = sample(1:2,n,replace=T). 对于n=50和 对于 功能x = rnorm(n), y=rnorm(n)

然后我创建了一个数据框,以便我可以看到 x,y 及其随机分配的集群。

data = data.frame(x,y,cluster)

然后我得到了结果:

           x          y    cluster
1  -0.89691455  0.41765075   2
2   0.18484918  0.98175278   1
3   1.58784533 -0.39269536   1
4  -1.13037567 -1.03966898   1
5  -0.08025176  1.78222896   2
6   0.13242028 -2.31106908   2
7   0.70795473  0.87860458   2
8  -0.23969802  0.03580672   1
9   1.98447394  1.01282869   2
10 -0.13878701  0.43226515   2

我现在想做的是获得集群的平均值。也就是说,集群 1 和 2 的平均值是多少?

所以我所做的是:

m1 = sum(data[data$C==1])/sum(data$cluster==1)

这并没有给我想要的价值。我所期待的是集群 1 和 2 中 x 和 y 的所有值的平均值。

标签: r

解决方案


我们可以尝试sapply通过对每个unique集群上的数据框进行子集化,然后获取mean数据框中所有值的值。

with(data, sapply(sort(unique(cluster)), function(x) 
             mean(unlist(data[cluster == x, -3]))))

#[1] -0.1236613 -0.1849584

或类似地split

sapply(split(data[1:2], data$cluster), function(x) mean(unlist(x)))

#         1          2 
#-0.1236613 -0.1849584 

我们也可以

with(data, tapply((x + y) / 2, cluster, mean))  #suggested by @Gregor

或者

aggregate((x+y)/2~cluster,data, mean)

正如@Gregor 在评论中提到的那样,您可以创建一个新列,(x + y)/2)并且可以轻松进行计算。

数据

set.seed(1234)
n=50
data = data.frame(x = rnorm(n), y=rnorm(n),cluster = sample(1:2,n,replace=T))

推荐阅读