gpt4 book ai didi

r - 如何计算列中每个类别的份额?

转载 作者:行者123 更新时间:2023-12-01 23:29:55 24 4
gpt4 key购买 nike

df = data.frame(week = as.factor(rep(c(1, 2), times = 5)),
name = as.factor(rep(LETTERS[1:5], times = 2)),
count = rpois(n = 10, lambda = 20))

> df
week name count
1 1 A 16
2 2 B 14
3 1 C 23
4 2 D 15
5 1 E 12
6 2 A 15
7 1 B 23
8 2 C 22
9 1 D 22
10 2 E 26

我想计算每个名字每周的计数份额。
起初我打算使用以下方法:
transform(df, week1_share = ifelse(week == "1", round((df$count / sum(df$count)  * 100),2), NA))
transform(df, week2_share = ifelse(week == "2", round((df$count / sum(df$count) * 100),2), NA))

但是然后让每一列合并,最终把它作为条形图上的标签,似乎效率太低了。必须有某种类型的快速解决方案,我还不知道。

基本上我想做的是如下但添加可能已按上述计算出的份额%以匹配每个框。
ggplot(df, aes(reorder(week, -count),count, color = "white", group = name, fill = name))+
geom_bar(position = "stack", stat = "identity") +
scale_y_continuous(labels=comma)+
ggthemes::scale_color_tableau()

enter image description here

我不知道为什么重新排序功能经常在我身上失败。如果您有在 desc 中排序的任何提示,请分享。

最佳答案

您提供的数据已被用于:

# Loading the required data
df = data.frame(week = as.factor(rep(c(1, 2), times = 5)),
name = as.factor(rep(LETTERS[1:5], times = 2)),
count = rpois(n = 10, lambda = 20))

使用 plyr包装函数、百分比和标记的相对位置已经计算。
#Loading the required packages    
library(plyr)
library(ggplot2)

# Calculating the percentages
df = ddply(df, .(week), transform, percent = round(count/sum(count) * 100))

# Calculating the position for plotting
df = ddply(df, .(week), transform, pos = cumsum(percent) - (0.5 * percent))

使用上面计算的信息,绘图已经完成。
# Basic graph
p10 <- ggplot() + geom_bar(aes(y = percent, x = week, fill = name),
data = df, stat="identity")

# Adding data labels
p10 <- p10 + geom_text(data=df, aes(x = week, y = pos,
label = paste0(percent,"%")), size=4)
p10

这是您一直在寻找的吗?

enter image description here

关于r - 如何计算列中每个类别的份额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40523139/

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