按组计算标准差,不包括R

时间:2018-05-28 12:38:11

标签: r

很容易计算R数据帧中每个组的平均值。如果您想排除当前观察,it is almost as easy

在计算标准差时,有没有简单的方法可以排除当前的观察结果?

例如,当我有这张表时

data.frame(country = c(rep("A",3), rep("B",3)), weight = c(10,11,12,20,25,30))

,我需要下表:

data.frame(country = c(rep("A",3), rep("B",3)), weight = c(10,11,12,20,25,30), standarddeviation = c(sd(c(11,12)), sd(c(10,12)), sd(c(10,11)), sd(c(25,30)), sd(c(20,30)), sd(c(20,25))))

2 个答案:

答案 0 :(得分:3)

选项是使用dplyrmapplymapply为每一行(组)运行,sd计算排除当前行。

library(dplyr)

df %>% group_by(country) %>%
  mutate(Sp_SD = mapply(function(x)sd(weight[-x]), 1:n()))


# # A tibble: 6 x 3
# # Groups: country [2]
# country weight Sp_SD
# <fctr>   <dbl> <dbl>
# 1 A         10.0 0.707
# 2 A         11.0 1.41 
# 3 A         12.0 0.707
# 4 B         20.0 3.54 
# 5 B         25.0 7.07 
# 6 B         30.0 3.54 

答案 1 :(得分:0)

不是一个非常漂亮的解决方案,但它应该有效

library(dplyr)

data = data.frame(country = c(rep("A",3), rep("B",3)), weight = c(10,11,12,20,25,30))

cdata = list()

for(k in 1:length(unique(data$country))){
cdata[[k]] = filter(data,country==unique(country)[k])
}

for(i in 1:length(unique(data$country))){
  for(j in 1:nrow(cdata[[1]])){
    aux=cdata[[i]][-j,]
    cdata[[i]][j,"StandardDeviation"] = sd(aux$weight)
  }
}

rbind(cdata[[1]],cdata[[2]])