Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find the total of frequency based on the values of a factor column in R?
Often, we have duplicate values in a factor column that means a factor column has many levels and each of these levels occur many times. In this situation, if we have a frequency column then we want to find the total of that frequency based on the values of a factor column and this can be done by using aggregate function.
Example
> Metal<-rep(c("Iron","Nickel","Lead","Zinc","Tin","Sodium","Silver"),times=5)
> Quantity<-sample(20:50,35,replace=TRUE)
> df2<-data.frame(Metal,Quantity)
> head(df2,10)
Metal Quantity 1 Iron 43 2 Nickel 33 3 Lead 25 4 Zinc 24 5 Tin 27 6 Sodium 34 7 Silver 31 8 Iron 37 9 Nickel 36 10 Lead 24 > tail(df2,10) Metal Quantity 26 Tin 49 27 Sodium 43 28 Silver 47 29 Iron 28 30 Nickel 41 31 Lead 21 32 Zinc 33 33 Tin 44 34 Sodium 34 35 Silver 33
> aggregate(df2["Quantity"],by=df2["Metal"],sum)
Output
Metal Quantity 1 Iron 157 2 Lead 148 3 Nickel 174 4 Silver 165 5 Sodium 161 6 Tin 192 7 Zinc 155
Advertisements
