如何在dplyr中使用group_by()和do()为每个因子级别应用函数

如何在dplyr中使用group_by()和do()为每个因子级别应用函数,r,function,dplyr,R,Function,Dplyr,我写了一个函数(weighted.sd),它给了我一些加权统计数据(比如均值、标准差和95%的置信区间)。我想将此函数应用于因子变量(区域)的每个级别,然后在带有误差条的ggplot2图形中使用每个区域的加权统计(因此为95%置信区间) 我也尝试了tapply和for循环。但是我没有做对。而且,我喜欢尽可能多地使用dplyr,因为它很容易阅读和理解 以下是我的最佳尝试: #example data data<-as.data.frame(cbind(rnorm(1:50),as.fact

我写了一个函数(weighted.sd),它给了我一些加权统计数据(比如均值、标准差和95%的置信区间)。我想将此函数应用于因子变量(区域)的每个级别,然后在带有误差条的ggplot2图形中使用每个区域的加权统计(因此为95%置信区间)

我也尝试了tapply和for循环。但是我没有做对。而且,我喜欢尽可能多地使用dplyr,因为它很容易阅读和理解

以下是我的最佳尝试:

#example data 
data<-as.data.frame(cbind(rnorm(1:50),as.factor(rnorm(1:50)),rnorm(1:50)))
colnames(data)<-c("index_var","factor_var","weight_var") 

weighted.sd <- function(x,weight){
  na <- is.na(x) | is.na(weight)
  x <- x[!na]
  weight <- weight[!na]  
  sum.w <- sum(weight)
  sum.w2 <- sum(weight^2)
  mean.w <- sum(x * weight) / sum(weight)
  x.var.w<-    (sum.w / (sum.w^2 - sum.w2)) * sum(weight * (x - mean.w)^2)
  x.sd.w<-sqrt((sum.w / (sum.w^2 - sum.w2)) * sum(weight * (x - mean.w)^2))
  SE<- x.sd.w / sqrt(sum(weight))
  error <- qnorm(0.975)*x.sd.w/sqrt(sum(weight))
  left <- mean.w-error
  right <- mean.w+error  
  return(cbind(mean.w,x.sd.w,SE,error,left,right))
}

test<- data %>% 
  group_by(factor_var) %>% 
  do(as.data.frame(weighted.sd(x=index_var,weight=weight_var)))
test

dplyr
中使用
do
时,您需要将其与
一起使用$
才能像这样工作:

test<- data %>% 
  group_by(factor_var) %>% 
  do(as.data.frame(weighted.sd(x=.$index_var,weight=.$weight_var)))
test
但是,这里的数据不是很好,因为负权重(
data$weight\u var
)会产生上述NAN。特别是
sqrt(负数)
部分

test<- data %>% 
  group_by(factor_var) %>% 
  do(as.data.frame(weighted.sd(x=.$index_var,weight=.$weight_var)))
test
> test
Source: local data frame [50 x 7]
Groups: factor_var [50]

   factor_var      mean.w x.sd.w    SE error  left right
        (dbl)       (dbl)  (dbl) (dbl) (dbl) (dbl) (dbl)
1           1  1.79711934    NaN   NaN   NaN   NaN   NaN
2           2 -0.70698012    NaN   NaN   NaN   NaN   NaN
3           3 -0.85125760    NaN   NaN   NaN   NaN   NaN
4           4 -0.93903314    NaN   NaN   NaN   NaN   NaN
5           5  0.09629631    NaN   NaN   NaN   NaN   NaN
6           6  1.02720022    NaN   NaN   NaN   NaN   NaN
7           7  1.35090758    NaN   NaN   NaN   NaN   NaN
8           8  0.67814249    NaN   NaN   NaN   NaN   NaN
9           9 -0.28251464    NaN   NaN   NaN   NaN   NaN
10         10  0.38572499    NaN   NaN   NaN   NaN   NaN
..        ...         ...    ...   ...   ...   ...   ...