首页 > 解决方案 > R中一组完整数据帧的方差

问题描述

假设我有一个包含 10+1 列和 10 行的数据框,并且每个值都具有相同的单位,除了一列(“分组”列 A)。我正在尝试完成以下任务:给定基于最后一列的数据帧分组,我如何将整个块的标准偏差计算为单个整体变量。

假设我进行分组(实际上是cut间隔):

df %>% group_by(A)

根据我在本网站上收集到的信息,您可以使用聚合或其他 dplyr 方法来计算每列的方差,即: this(如果我有 <10 个代表,则不会让我嵌入)。在该图中,我们可以将分组视为颜色,但通过使用聚合,我将获得每个指定列的 1 个标准偏差(我知道您可以使用它cbind来获得多个变量,例如)和每个组(以及使用and的aggregate(cbind(V1,V2)~A, df, sd)类似方法,附在末尾)。dplyr%>%summarise(..., FUN=sd)

但是我想要的是就像在 Matlab 中一样

group1 = df(row_group,:) % row_group would be df(:,end)==1 in this case
stdev(group1(:)) % operator (:) is key here
% iterate for every group

我有理由希望以这种特定方式使用它,当然真实的数据框比这个模拟示例要大。

最小工作示例:

df <- data.frame(cbind(matrix(rnorm(100),10,10),c(1,2,1,1,2,2,3,3,3,1)))
colnames(df) <- c(paste0("V",seq(1,10)),"A")

df %>% group_by(A) %>% summarise_at(vars(V1), funs(sd(.))) # no good
aggregate(V1~A, data=df, sd) # no good
aggregate(cbind(V1,V2,V3,V4,V5,V6,V7,V8,V9,V10)~A, data=df, sd) # nope
df %>% group_by(A) %>% summarise_at(vars(V1,V2,V3,V4,V5,V6,V7,V8,V9,V10), funs(sd(.))) # same as above...

结果应该是 3 个双打,每个都有组的 sd(如果添加了足够的列,应该接近 1)。

标签: rdplyraggregate

解决方案


If you want a base R solution, try the following.

sp <- split(df[-1], cut(df$A, breaks=c(2.1)))
lapply(sp, function(x) var(unlist(x)))
#$`(0.998,2]`
#[1] 0.848707
#
#$`(2,3]`
#[1] 1.80633

I have coded it in two lines to make it clearer but you can avoid the creation of sp and write the one-liner

lapply(split(df[-1], cut(df$A, breaks=c(2.1))), function(x) var(unlist(x)))

Or, for a result in another form,

sapply(sp, function(x) var(unlist(x)))
#(0.998,2]     (2,3] 
# 0.848707  1.806330

DATA

set.seed(6322)    # make the results reproducible
df <- data.frame(cbind(matrix(rnorm(100),10,10),c(1,2,1,1,2,2,3,3,3,1)))
colnames(df) <- c(paste0("V",seq(1,10)),"A")

推荐阅读