如何制作一个函数来计算“患病率”;1“;在列中包含';0';和';1';只做图形? Group1
我建议下一种方法使用如何制作一个函数来计算“患病率”;1“;在列中包含';0';和';1';只做图形? Group1,r,ggplot2,aggregate,R,Ggplot2,Aggregate,我建议下一种方法使用dplyr和ggplot2。您必须通过按Group1和Group2分组来处理数据,以获得总值,并根据Group2计算百分比。接下来的代码包括使用summary()和mutate()函数的步骤: Group1 <- c('A','A','A','A','B','B','B','B') Group2 <- c('1','1','2','1','2','1','1','2','1','2','2','2','2','1','1','2') Value <- c('
dplyr
和ggplot2
。您必须通过按Group1
和Group2
分组来处理数据,以获得总值,并根据Group2
计算百分比。接下来的代码包括使用summary()
和mutate()
函数的步骤:
Group1 <- c('A','A','A','A','B','B','B','B')
Group2 <- c('1','1','2','1','2','1','1','2','1','2','2','2','2','1','1','2')
Value <- c('1','0','0','1','1','0','0','0','0','1','1','1','1','0','1','0')
df <- data.frame(Group1,Group2,Value)
库(ggplot2)
图书馆(dplyr)
#资料
集团1%
#密谋
ggplot(aes(x=Group2))+
几何图形条(stat='identity',aes(y=百分比,fill=Group1),position=位置减淡(0.9))+
主题_bw()
输出接近您想要的:
这对我帮助很大。谢谢大家!@太好了!如果您认为此答案对您有帮助,您可以单击此答案左侧的勾号接受此答案:)
library(ggplot2)
library(dplyr)
#Data
Group1 <- c('A','A','A','A','B','B','B','B')
Group2 <- c('1','1','2','1','2','1','1','2','1','2','2','2','2','1','1','2')
Value <- c('1','0','0','1','1','0','0','0','0','1','1','1','1','0','1','0')
df <- data.frame(Group1,Group2,Value,stringsAsFactors = F)
df$Value <- as.numeric(df$Value)
#Compute
df %>% group_by(Group1,Group2) %>%
#Compute totals
summarise(Val=sum(Value)) %>%
#Compute percentages
group_by(Group2) %>% mutate(Percentage=Val/sum(Val)) %>%
#Plot
ggplot(aes(x=Group2))+
geom_bar(stat='identity',aes(y=Percentage,fill=Group1),position = position_dodge(0.9))+
theme_bw()