How to consolidate the less relevant rows of my df in R?

Viewed 31

This is my df:

  col1 col2 
1   a    20%  
2   b    20% 
3   c    15% 
4   d    10% 
5   e     9%  
6   f     8%  
7   g     7%  
8   h     6%  
9   h     5%  

And I would like to have something like this

     col1    col2 
1       a     20%  
2       b     20% 
3       c     15% 
4       d     10% 
5   other     35% 

I tried using dplyr to solve this, but I got no success.

1 Answers

You can use fct_collapse() from the forcats package.

library(tidyverse)

df <- tribble(
  ~col1, ~col2,
  "a", 20,
  "b", 20,
  "c", 15,
  "d", 10, 
  "e", 9,  
  "f", 8,  
  "g", 7,  
  "h", 6,  
  "h", 5
  )

df$col1 <- fct_collapse(
  df$col1,
  a = "a",
  b = "b",
  c = "c",
  d = "d",
  other_level = "other")

df %>%
  group_by(col1) %>%
  summarise(col2 = sum(col2))
Related