【发布时间】:2021-05-17 21:51:54
【问题描述】:
我想为下面两个变量 y1 和 y2 的数据计算 2 个基本统计数据。
首先,对于每个group,我想分别获得variance*n_of_group-1(例如,对于group==1,答案将是y1上的6和y2上的2)。
其次,对于每个group,我想分别获得covariance*n_of_group-1(例如,对于group==1,答案将是0)。
我已经尝试了一些东西,但我想知道如何将*n_of_group-1 部分应用到我下面的 R 代码中?
ps. n_of_group 就是每个组的count() 或n()。
我的想要的输出如下所示。
z <- "group y1 y2
1 1 2 3
2 1 3 4
3 1 5 4
4 1 2 5
5 2 4 8
6 2 5 6
7 2 6 7
8 3 7 6
9 3 8 7
10 3 10 8
11 3 9 5
12 3 7 6"
dat <- read.table(text = z, header = T)
dat %>%
group_by(group) %>%
summarise(var1 = var(y1), var2 = var(y2)) # how to apply the `*n_of_group-1` to var1 & var2
dat %>%
group_by(group) %>%
summarise(co = cov(y1,y2)) # how to apply the `*n_of_group-1` to co, what if `co` was more than 1 number
期望的输出(如果我们将上面每个组的结果放在一个 2x2 矩阵中):
group1 = matrix(c(6,0,0,2),2) # The two repetitive element in the middle (0,0) are
# the second statistic, the other elements are the
# first statistics
group2 = matrix(c(2,-1,-1,2),2)
group3 = matrix(c(6.8,2.6,2.6,5.2),2)
【问题讨论】:
-
你是如何得到那些
matrix输出的
标签: r dataframe dplyr statistics tidyverse