簡體   English   中英

R數據幀-一次聚合多列

[英]R data frame - aggregating multiple columns at once

使用如下數據框df

----------------------
a     |  b    |  c 
------+-------+-------
true  | true  | true
false | true  | false
false | false | false
true  | true  | false

我需要為數據列a,b和c找到"true"的百分比,以便可以在ggplot中使用它。 怎么做呢?

注: - "true"是不是邏輯TRUE

我們使用gather將“寬”格式重塑為“長”格式,然后為每個“組”找到“真”的mean ,然后使用geom_bar進行條形圖繪制

library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
gather(df1, group, value) %>% 
       group_by(group) %>% 
       summarise(perc= mean(value=="true")) %>% 
       ggplot(., aes(x=group, y=perc)) + 
               geom_bar(stat="identity") +
               scale_y_continuous(labels = percent)

注意:假定列是character

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM