TransWikia.com

Recoding groups to create a summary accordingly

Stack Overflow Asked by rjunkie2 on December 23, 2021

I have a data like table below

Category Value
14        1
13        2
32        1
63        4
24        1
77        3
51        2
19        4
15        1
24        4
32        3
10        1
.         .
.         .
so on 

actually i want to create a group of variables like

C1= (14,13,24,19,77)
C2= (32,51,63,15,10)
c3= (......)
c4= (...)

so that it will create a dataframe like (Recoding kind of thing)

C1  c2  c3  c4......
14  32  
13  51
24  63
15  10

after this i can create a summary

df<- df[!is.na(df[[cols]]), ]
sum1 <- as.data.frame(table(df[[cols]]))

Final Expected output should be like

   C1  C2 C3 ....
1  22%
2  13%
3  42%
4  15%
N  94

N is total number of counts for that particular groups.

One Answer

You can create a column to group various values from C1, C2 etc and give them their respective value. We can then get the data in wide format. You can use adorn_totals from janitor to get sum of each column added in the last row.

library(dplyr)

df %>%
  group_by(col = case_when(Category %in% C1 ~ 'C1', 
                           Category %in% C2 ~ 'C2')) %>%
  mutate(Value = row_number()) %>%
  tidyr::pivot_wider(names_from = col, values_from = Category) %>%
  janitor::adorn_totals()

Answered by Ronak Shah on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP