【问题标题】:Percentages of a variable in another variable using dplyr and creating a boxplot with standard deviation使用 dplyr 并创建具有标准偏差的箱线图的变量在另一个变量中的百分比
【发布时间】:2018-12-05 12:09:22
【问题描述】:

我有这个 df。我希望将眼镜制作成一个 1.5 的因子。此后我想检查两个级别中有多少百分比的ciss值高于16。每个级别都被视为一组,因此应该算作100%。

glasses <- c(1.0,1.1,1.1,1.6,1.2,1.7,2.2,5.2,8.2,2.5,3.0,3.3,3.0,3.0)
ciss <- c(2,9,10,54,65,11,70,54,0,65,8,60,47,2)
df <- cbind(glasses, ciss)
df

我想要一个看起来像这样的结果

glasses    Percentages ciss > 16
<=1.5      xx%
>1.5       xx%

我尝试使用dplyr

dfnew <- df %>% mutate(ani=cut(glasses, breaks=c(-Inf, 1.5, Inf), 
                         labels=c("<=1.5",">1.5")))
dfnew %>% group_by(ani) %>% mutate(perc = ciss>16 / sum(ciss))

最后,我想演示一下箱线图中的百分比(x 轴上的眼镜,y 轴上 16 以上 ciss 的百分比)。

【问题讨论】:

    标签: r ggplot2 dplyr geom-bar


    【解决方案1】:

    试试这个。

    require(tidyverse)
    require(ggplot2)
    require(reshape2)
    
    #Input data
    glasses = c(1.0,1.1,1.1,1.6,1.2,1.7,2.2,5.2,8.2,2.5,3.0,3.3,3.0,3.0)
    ciss = c(2,9,10,54,65,11,70,54,0,65,8,60,47,2)
    
    #Bind in dataframe
    df = as.data.frame(cbind(glasses,ciss))
    
    df %>%
       mutate(typglass = if_else(glasses > 1.5,">1.5","<=1.5")) %>%
       filter(ciss > 16) %>%
       group_by(typglass) %>%
       summarise (n = n()) %>%
       mutate(freq = n / sum(n)) %>%
       ggplot() +
       geom_bar(aes(x = typglass, y = freq, fill = typglass), stat = "identity", width = 0.5) +
       theme_classic()
    

    给出以下结果:

    【讨论】:

    • 如果可以的话,您可以为答案添加投票。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多