gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:04:37 24 4
gpt4 key购买 nike

我写了一个函数 (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

这会导致错误消息(抱歉,其中一部分是德语,但您可以使用代码重现它):
   Error in as.data.frame(weighted.sd(x = index_var, weight = weight_var)) : 
Fehler bei der Auswertung des Argumentes 'x' bei der Methodenauswahl
für Funktion 'as.data.frame': Error in weighted.sd(x = index_var, weight = weight_var) :
object 'index_var' not found

最佳答案

使用时 dodplyr您需要与 .$ 一起使用它为了像这样工作:

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
.. ... ... ... ... ... ... ...

但是,这里的数据不是很好,因为负权重 ( data$weight_var ) 会产生上述 NAN。特别是 sqrt(negative number)部分。

关于r - 如何在 dplyr 中使用 group_by() 和 do() 为每个因子级别应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33153654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com