如何计算Y表示X = 1的平均值

问题描述 投票:0回答:2

我试图找出集群,这是我一直在使用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)

这不给我我想要的价值。我所期待的是从平均x和y组合在簇1和2的所有值。

r
2个回答
2
投票

我们可以尝试使用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))

1
投票

这里有一个tidyverse方法。通过cluster转换为长格式和组。

Solution

data %>% 
  gather(var, value, -cluster) %>% 
  group_by(cluster) %>% 
  summarize(mean = mean(value))

# A tibble: 2 x 2
  cluster     mean
    <int>    <dbl>
1       1 -0.00152
2       2  0.327 

Data

data <- read.table(header = T, stringsAsFactors = F, text = "
x          y    cluster
-0.89691455  0.41765075   2
0.18484918  0.98175278   1
1.58784533 -0.39269536   1
-1.13037567 -1.03966898   1
-0.08025176  1.78222896   2
0.13242028 -2.31106908   2
0.70795473  0.87860458   2
-0.23969802  0.03580672   1
1.98447394  1.01282869   2
-0.13878701  0.43226515   2")
© www.soinside.com 2019 - 2024. All rights reserved.