一个变量在另一个变量中的百分比使用 dplyr 并创建具有标准差的箱线图

Percentages of a variable in another variable using dplyr and creating a boxplot with standard deviation

我有这个df。我希望将眼镜变成一个水平 <=1.5 和 >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 百分比)。

试试这个。

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()

给出以下结果: