I need to group by variable x or variable y depending upon a condition. This is not happening when I use a magrittr pipe.
Consider a dataframe df1:
> df1
seat_id student_id seat_state
1 1222 500 9
2 850 500 9
3 850 500 9
4 1225 500 9
5 16502 500 9
6 17792 500 9
7 17792 500 9
8 1219 501 10
9 847 501 9
10 847 501 9
11 1220 501 9
12 17785 501 9
13 17785 501 9
14 1214 502 9
15 842 502 9
16 842 502 9
17 1215 502 9
18 1211 503 9
19 839 503 9
20 839 503 9
Now suppose I want to summarise this in two ways 1. By student_id or 2. By seat_state Depending upon a variable
summary
The old and long way is
if (summary==1) df1 %>% group_by(student_id) %>% summarise(seats=n()) else if (summary==2) df1 %>% group_by(seat_state) %>% summarise(seats=n())
But there has to be a more compact way especially because I have several magrittr pipes coming after the summarise statement and therefore will double the size of the code.