R-基于另一列中的条目的列的最高标准偏差/方差

时间:2016-06-16 01:06:33

标签: r

我是R的初学者。我正在使用一个包含多列的数据框,我想根据第2列中的条目计算第1列的最高方差或标准差。 例如,如果我的数据集如下所示,我想分别计算学校A,学校B和学校C的最高标准差。

School City Percent
A       X     92
B       Y     80
C       Z     95
A       X     89
B       Y     75

2 个答案:

答案 0 :(得分:2)

在基数R中,函数ave()可用于根据data.frame中的不同组添加具有从其他列派生的数量的列。

以下是一个例子:

df1$var <- with(df1, ave(Percent, School, FUN=var))
df1$sd <- with(df1, ave(Percent, School, FUN=sd))
> df1
#  School City Percent  var       sd
#1      A    X      92  4.5 2.121320
#2      B    Y      80 12.5 3.535534
#3      C    Z      95   NA       NA
#4      A    X      89  4.5 2.121320
#5      B    Y      75 12.5 3.535534

可以使用which.max()提取具有最大值的条目:

df1[which.max(df1$var),]
#  School City Percent  var       sd
#2      B    Y      80 12.5 3.535534

另一个基本R选项是使用aggregate()。这将以更紧凑的形式表示结果:

df2 <- setNames(aggregate(Percent~School, df1, var), c("School", "Percent.var"))
> df2
#  School Percent.var
#1      A         4.5
#2      B        12.5
#3      C          NA

df2 <- setNames(aggregate(Percent~School, df1, sd), c("School", "Percent.sd"))
> df2
#  School Percent.sd
#1      A   2.121320
#2      B   3.535534
#3      C         NA

或者,两个aggregate操作合并:

df2 <- setNames(do.call(data.frame,
                aggregate(Percent~School, df1, function(x) c(var(x),sd(x)))),
                c("School","Percent.var","Percent.sd"))
#  School Percent.var Percent.sd
#1      A         4.5   2.121320
#2      B        12.5   3.535534
#3      C          NA         NA

在这些情况下,也可以使用which.max()从输出中提取最大值:

df2[which.max(df2$Percent.sd),]
#  School Percent.var Percent.sd
#2      B        12.5   3.535534

此示例中使用的数据:

df1 <- structure(list(School = structure(c(1L, 2L, 3L, 1L, 2L), 
                 .Label = c("A", "B", "C"), class = "factor"), 
                 City = structure(c(1L, 2L, 3L, 1L, 2L), 
                 .Label = c("X", "Y", "Z"), class = "factor"), 
                 Percent = c(92L, 80L, 95L, 89L, 75L)), 
                 .Names = c("School", "City", "Percent"), 
                 class = "data.frame", row.names = c(NA, -5L))

答案 1 :(得分:1)

这将分别计算每所学校(A,B,C)的标准差

df<-data.frame(school=c("A","B","C","A","B"),percent=c(92,80,95,89,75))

library(dplyr)
result<-split(df,df$school)%>%lapply(.,function(x)sd(x$percent))%>%unlist(.)%>%as.data.frame(.)
res<-cbind(row.names(result),result)
colnames(res)<-c("school","std_dev")
res


#output
> res
  school  std_dev
A      A 2.121320
B      B 3.535534
C      C       NA