0

My dataframe df is
District State Mode
A State1 Cycle
D State2 Car
A State1 Cart
C State1 Walk
B State1 Car
I want to count the modes of transport in each district.

I want the output like this:
District State Cycle Car Cart Walk
A State1 1 0 1 0
B State1 0 1 0 0
C State1 0 0 0 1
D State2 0 1 0 0
I tried using aggregate and table.

grouped_data <- aggregate(df, by=list(df$district, df$Mode,df$State), FUN=length) 
grouped_data<-as.data.frame(table(df))

But it is not giving me the desired output.I also would like the percentages for each mode to be displayed as separate columns.

Sowmya Kannan
  • 75
  • 1
  • 4
  • `df %>% count(District, Mode) %>% pivot_wider(names_from = Mode, values_from = n, values_fill = list(n = 0))` – Ronak Shah Feb 20 '20 at 09:28
  • This works. Thank you. How do I get the percentages as well in separate columns just like the counts? Also, I would like to retain the state column. – Sowmya Kannan Feb 20 '20 at 09:48
  • `df %>% count(District, State, Mode) %>% pivot_wider(names_from = Mode, values_from = n, values_fill = list(n = 0))` – Ronak Shah Feb 20 '20 at 10:58

0 Answers0