How to use data.table In R Language

data.table package to calculate the sum of points scored by a team.

R




library(data.table) 
  
# convert data frame to data table 
setDT(df)
  
# find sum of points scored by sub 
df[ ,list(sum=sum(Marks)), by=Sub]


Output:

Sub sum
Math 10
Phy 22
Che 8


How to Calculate the Sum by Group in R?

In this article, we are going to see how to calculate the Sum by Group in R Programming Language.

Data for Demonstration

R




# creating data frame
df <- data.frame(Sub = c('Math', 'Math', 'Phy', 'Phy'
                         'Phy', 'Che', 'Che'),
                 Marks = c(8, 2, 4, 9, 9, 7, 1),
                 Add_on = c(3, 1, 9, 4, 7, 8, 2))
  
# view dataframe
df


Output:

Sub    Marks    Add_on
Math    8    3
Math    2    1
Phy    4    9
Phy    9    4
Phy    9    7
Che    7    8
Che    1    2

Similar Reads

Method 1: Using aggregate() method in Base R

...

Method 2: Using dplyr() package

aggregate() function is used to get the summary statistics of the data by group. The statistics include mean, min, sum. max etc....

Method 3: Using data.table

...

Contact Us