gpt4 book ai didi

r - 在 ggplot2 中引导一个比例(因子水平)

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

我有一个长格式数据框,其中行代表不同人的响应(四个类别之一)。这里提供了一个示例数据集:

df <- data.frame(person=c(rep("A",100),rep("B",100)),resp=c(sample(4,100,replace=TRUE),sample(4,100,replace=TRUE)))
df$resp <- factor(df$resp)
summary(df)
person resp
A:100 1:52
B:100 2:55
3:54
4:39

我想展示一个图表,其中 x 轴绘制响应类别,y 轴显示某个类别中响应的比例,以及通过引导(带替换采样)计算误差线的位置。

我可以计算比例(以一种非常笨拙的方式;我相信这可以改进,但这不是我主要关心的问题):
pFrame <- ddply(df,.(person,resp),summarise,trials = length(resp))
# can't figure out how to calculate the proportion with plyr.
pFrame$prop <- NA
people <- unique(df$person)
responses <- unique(df$resp)
for (i in 1 : length(people)){
nTrials <- nrow(subset(df,person==people[i]))
for (j in 1 : 4){
pFrame$prop[pFrame$person==people[i] & pFrame$resp==responses[j]] <- pFrame$trials[pFrame$person==people[i] & pFrame$resp==responses[j]] / nTrials
}
}

并绘制它:
ggplot(pFrame,aes(x=resp,y=prop,colour=person)) + geom_point()

但我真的很想使用类似 stat_summary(fun.data="mean_cl_boot") 的东西显示比例的可变性(即作用于原始数据框 df ,并引导行)。我尝试了一些创建自定义函数的尝试,但这似乎并不简单,因为需要首先为 bootstrap 转换因子级别。

最佳答案

我无法让 ggplot 的“mean_cl_boot”工作。不过,这是一个替代解决方案:

library(boot)

summary_for_plot <- melt(prop.table(table(df), 1))
names(summary_for_plot) <- c("person", "resp", "V1")

# function for boot()
summary_function <- function(df, d){
melt(prop.table(table(df[d,]), 1))[, 3]
}

bootres <- boot(df, statistic = summary_function, R=100)
# get the standard deviation, used for the confidence intervals
summary_for_plot$sd <- sd(bootres$t)

ggplot(summary_for_plot, aes(x= resp, y = V1, color = person)) + geom_point() +
geom_errorbar(aes(ymin = V1-sd, ymax = V1+sd), width = 0.2)

关于r - 在 ggplot2 中引导一个比例(因子水平),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11717645/

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