Nicolas
Nicolas

Reputation: 117

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.

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

Upvotes: 0

Views: 78

Answers (3)

akrun
akrun

Reputation: 887851

Using aggregate from base R

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

Upvotes: 0

Agaz Wani
Agaz Wani

Reputation: 5694

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  

Upvotes: 1

DaveArmstrong
DaveArmstrong

Reputation: 22034

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  

Upvotes: 1

Related Questions