r - 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)。
解决方案
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")
推荐阅读
- c# - 即使在侦听器关闭后,C# HttpListener getContext 方法也会继续阻塞
- google-apps-script - 无法获取由谷歌驱动器上的另一个应用程序脚本创建的文件夹
- java - Spring Reactive Web 更新方法创建新记录而不是更新现有记录
- cpu-architecture - 给定某个内存位置的二进制模式,是否可以判断该模式代表机器指令还是数字?
- docker - 如何在 Heroku 上为 Docker 设置动态环境变量?
- java - 下载springframework源码导入idea成功,创建测试模块,依赖不生效
- excel - 在不同的应用程序中关闭工作簿后,一些实例仍然存在
- mysql - 错误:用户 'root'@'localhost' 的访问被拒绝(使用密码:是)
- bash - 捕获和平均 ping 时间
- math - 查找长度为 x2-x1 的多边形和水平线段之间的交点数