'How do I get "modes' with respect to another column in R?
As the title suggests, I need mode of a particular column W.R.T categories in another column
> table(data$Outlet_Size)
High Medium Small
1606 621 1862 1592
> table(data$Outlet_Type)
Grocery Store Supermarket Type1 Supermarket Type2 Supermarket Type3
722 3717 618 624
so, I want to find out what are the stores sizes W.R.T the types of these stores
Solution 1:[1]
You can do the following:
library(dplyr)
data %>%
filter(!is.na(Outlet_Size)) %>% #(Optional to exclude NA from mode)
count(Outlet_Type, Outlet_Size,name = "mode") %>%
group_by(Outlet_Type) %>%
slice_max(mode)
Output:
Outlet_Type Outlet_Size mode
<chr> <chr> <int>
1 Grocery Store Small 257
2 Supermarket Type1 Medium 250
3 Supermarket Type2 Medium 260
4 Supermarket Type3 Small 249
Input:
set.seed(123)
data = pivot_longer(setnames(
as.data.frame(
lapply(1:3, \(x) {
sample(c("Grocery Store", "Supermarket Type1", "Supermarket Type2", "Supermarket Type3"),
1000, replace=T)
})),c("High", "Medium", "Small")
), everything(), names_to = "Outlet_Size", values_to = "Outlet_Type")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
