Original Data Frame
route user_type
A member
A casual
A member
A member
A member
B member
B casual
B member
C member
C member
Required new data frame
route user_type count_user_type
A member 4
A casual 1
B member 2
B casual 1
C member 2
I want to make a new data frame so that I can make a bar plot with route name on Y axis and count_user_type (filled by user_type) on X Axis, I used count(dataframe, route) from plyr package but it gave me the following result
route frequency
A 5
B 3
C 2
CodePudding user response:
You need to group_by
your relevant columns (i.e. to make specific combinations of them to count
) before doing a count
.
library(dplyr)
df %>% group_by(route, user_type) %>% count(name = "count_user_type")
# A tibble: 5 × 3
# Groups: route, user_type [5]
route user_type count_user_type
<chr> <chr> <int>
1 A casual 1
2 A member 4
3 B casual 1
4 B member 2
5 C member 2
CodePudding user response:
library(dplyr)
df %>% group_by(route, user_type) %>%
summarise(count_user_type= n())
CodePudding user response:
You can use the following code:
library(dplyr)
df %>%
group_by(route, user_type) %>%
summarise(count_user_type = n())
Output:
# A tibble: 5 × 3
# Groups: route [3]
route user_type count_user_type
<chr> <chr> <int>
1 A causal 1
2 A member 4
3 B causal 1
4 B member 2
5 C member 2
Data
df <- data.frame(route = c("A", "A", "A", "A", "A", "B", "B", "B", "C", "C"),
user_type = c("member", "causal", "member", "member", "member", "member", "causal", "member", "member", "member"))