简体   繁体   English

如何在 R 中按组计算某些变量的比例?

[英]How to count proportion of certain variable by group in R?

I would like to calaculate proportion of apperances of value == 1 to sum of counts of apperances by group class.我想计算价值 == 1 与 class 组的外观计数总和的比例。

Example data:示例数据:

   value  class
     0  urban
     0  urban
     1 forest
     0 forest
     0   lake
     1    sea
     1    sea
     0    sea

Expected result:预期结果:

  proportion_in_%  class
             0.0  urban
            50.0 forest
             0.0   lake
            66.6    sea

Code to make data:制作数据的代码:

data <- data.frame("value" = c(0,0,1,0,  0 , 1, 1, 0),
               "class" = c("urban", "urban", "forest", "forest", 
                           "lake", "sea", "sea", "sea"))

How about this这个怎么样

 data %>% group_by(class) %>% summarise(proportion = mean(value)*100) 
## A tibble: 4 x 2
#  class  proportion
#  <chr>       <dbl>
#1 forest       50  
#2 lake          0  
#3 sea          66.7
#4 urban         0  

Try this尝试这个

data %>%
  group_by(class) %>%
  summarize(Proportion_in_percent = (sum(value)*100)/n())

# A tibble: 4 x 2
  class  Proportion_in_percent
  <chr>                  <dbl>
1 forest                  50  
2 lake                     0  
3 sea                     66.7
4 urban                    0  

Using aggregate from base R使用来自base Raggregate

aggregate(cbind(Proption_in_percent = 100 *value) ~ class, data, FUN = mean )

-output -输出

#    class Proption_in_percent
#1 forest            50.00000
#2   lake             0.00000
#3    sea            66.66667
#4  urban             0.00000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM