Reputation: 57
I am attempting to count elements within a variable(column) and group it by elements in another variable.The table below is the current data I am working with:
. Company.Name Sales.Team Product.Family
1 example1 Global Accounts FDS
2 example2 Americas RDS
3 Example3 WEMEA 2 Research
4 Example4 WEMEA 2 Research
5 Example5 CEE Research
6 Example6 CEE Research
What I am trying to do is is aggregate count of company names by different product families. So it would look something like:
FDS RDS Research
Americas 0 1 0
CEE 0 0 2
Global Accounts 1 0 0
WEMEA 2 0 0 2
I have been messing around with the aggregate function, but this has not yielded the needed data. I am having trouble with determining how to have columns based on elements in a row.
Any help would be appreciated.
Upvotes: 0
Views: 135
Reputation: 288
You can solve this using the base table function in R. using an example table:
table(example_table$Sales.Team, example_table$Product.Family)
A basic run through for frequency tables can be found here at quick-R
Upvotes: 2
Reputation: 1268
If you need your output to be a dataframe, this is really easy using dplyr
.
library(dplyr)
my_df <- data.frame("Product.Family" = c("FDS", "RDS", rep("Research", 4)), "Company.Name" = paste0("Example", 1:6), "Sales.Team" = c("Global Accounts", "Americas", rep("WEMA 2", 2), rep("CEE", 2)))
summary_df <- my_df %>%
group_by(Sales.Team) %>%
summarize(FDS = sum(Product.Family == "FDS"), RDS = sum(Product.Family == "RDS"), Research = sum(Product.Family == "Research"))
Upvotes: 1