在R中按组获取标准偏差
我想得到R中各组的标准偏差(在本例中为同一属和同一物种)。但是,我的一些组由n=1组成,因此我无法计算标准偏差 这是一个看起来与我的真实数据集相似的随机数据集在R中按组获取标准偏差,r,R,我想得到R中各组的标准偏差(在本例中为同一属和同一物种)。但是,我的一些组由n=1组成,因此我无法计算标准偏差 这是一个看起来与我的真实数据集相似的随机数据集 x = structure(list(V1 = structure(c(1L, 2L, 2L, 3L, 3L), .Label = c("Genus1", "Genus2", "Genus3"), class = "factor"), V2 = structure(c(1L, 2L, 2L, 3L, 3L), .Label = c("
x = structure(list(V1 = structure(c(1L, 2L, 2L, 3L, 3L), .Label = c("Genus1",
"Genus2", "Genus3"), class = "factor"), V2 = structure(c(1L,
2L, 2L, 3L, 3L), .Label = c("Species1", "Species2", "Species3"
), class = "factor"), V3 = c(6.32, 8.43, 8.31, 9.29, 8.96)), class = "data.frame", row.names = c(NA, -5L))
像这样的期望输出?不确定处理n=1组的最佳方法
V1 V2 V3
Genus1 Species1
Genus2 Species2 0.084852814
Genus2 Species2
Genus3 Species3 0.233345238
Genus3 Species3
基尔
aggregate(x$V3,x[,c(“V1”,“V2”)],标准差)
#V1 V2 x
#1属1种1 NA
#2种规格2 0.08485281
#3属3种3 0.23334524
数据表
方法:
库(data.table)
as.data.table(x)[,(sigma=sd(V3)),by=(V1,V2)]
#V1 V2西格玛
#1:膝1种1 NA
#2:Genus2规格2 0.08485281
#3:Genus3规格3 0.23334524
Base R
aggregate(x$V3,x[,c(“V1”,“V2”)],标准差)
#V1 V2 x
#1属1种1 NA
#2种规格2 0.08485281
#3属3种3 0.23334524
数据表
方法:
库(data.table)
as.data.table(x)[,(sigma=sd(V3)),by=(V1,V2)]
#V1 V2西格玛
#1:膝1种1 NA
#2:Genus2规格2 0.08485281
#3:Genus3规格3 0.23334524
使用dplyr
,我们按“V1”、“V2”分组,并在“V3”上应用sd
,以获得“V3”的标准偏差
library(dplyr)
x %>%
group_by(V1, V2) %>%
summarise(V3 = sd(V3))
使用
dplyr
,我们按“V1”、“V2”分组,并在“V3”上应用sd
,以获得“V3”的标准偏差
library(dplyr)
x %>%
group_by(V1, V2) %>%
summarise(V3 = sd(V3))
尝试
x%>%groupby(V1)%>%summary(V3=sd(V3))
或aggregate(V3~V1,x,sd)
akrun解决方案需要包“dplyr”尝试x%>%groupby(V1)%>%summary(V3=sd(V3))
或aggregate(V3~V1,x,sd)
akrun解决方案需要包“dplyr”