- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sum a variable by factor levels in R?
We can do this by using aggregate function or with the help tapply
Example
> x <- data.frame(Category=factor(c("Graduation", "Graduation", "Post-Graduation", "Graduation","PhD", "Post-Graduation", "PhD")), Frequency=c(12,19,15,20,25,13,14)) > x Category Frequency 1 Graduation 12 2 Graduation 19 3 Post-Graduation 15 4 Graduation 20 5 PhD 25 6 Post-Graduation 13 7 PhD 14
Using aggregate
> aggregate(x$Frequency, by=list(Group=x$Category), FUN=sum) Group x 1 Graduation 51 2 PhD 39 3 Post-Graduation 28 Using tapply > tapply(x$Frequency, x$Category, FUN=sum) Graduation PhD Post-Graduation 51 39 28
- Related Articles
- How to rename the factor levels of a factor variable by using mutate of dplyr package in R?
- How to combine the levels of a factor variable in an R data frame?
- How to create a new column for factor variable with changed factor levels by using mutate of dplyr package in R?
- How to find the sum by distinct column for factor levels in an R data frame?
- How to find the column means by factor levels in R?
- How to print a factor vector without levels in R?
- How to find the cumulative sum for factor levels in an R data frame?
- How to convert factor levels into character in R?
- How to collapse factor levels in an R data frame?
- How to find the median for factor levels in R?
- How to find the sum by two factor columns in R?
- How to extract the factor levels from factor column in an R data frame?
- How to drop factor levels in subset of a data frame in R?
- How to find the number of levels in R for a factor column?
- How to create boxplot with multiple factor levels using ggplot2 in R?

Advertisements