Get Last value of each group in R

Last value of each group in R can be accomplished by aggregate() or group_by() function. Let’s see how to

  • Get last value of each group – groupby single column.
  • Get last value of each group – groupby multiple columns

First let’s create a dataframe

df1= data.frame(Name=c('James','Paul','Richards','Marico','Samantha','Ravi','Raghu','Richards','George','Ema','Samantha','Catherine'),
    State=c('Alaska','California','Texas','North Carolina','California','Texas','Alaska','Texas','North Carolina','Alaska','California','Texas'),
    Sales=c(14,24,31,12,13,7,9,31,18,16,18,14))
df1

df1 will be

Get Last value of a group in R 1

 

 

Get last value of each group in R :

Method 1:

Aggregate function which is grouped by state and name, along with function last is mentioned to get the last value of each group

# Get last value of each group in R

aggregate(df1$Sales, by=list(df1$State), FUN=last)

dataframe will be

Get Last value of a group in R 2a

Method 2:

Using group_by() function of dplyr package

# Get last value of each group in R

library(dplyr) 
df1 %>% group_by(State) %>% summarise(Last_value_sales = last(Sales))

dataframe will be

Get Last value of a group in R 2b

 

 

 

Get last value of each group in R  – Group by multiple colums in R:

Method 1:

# Get last value of each group in R – group by multiple columns

aggregate(df1$Sales, by=list(df1$State,df1$Name), FUN=last)

last value of dataframe grouped by state and name are

Get Last value of a group in R 3a

Method 2:

# Get last value of each group in R – group by multiple columns

library(dplyr) 
df1 %>% group_by(State,Name) %>% summarise(Last_value_sales = last(Sales))

Get Last value of a group in R 3b

                                                                                               

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts