Get First value of each group in R

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

  • Get first value of each group – groupby single column.
  • Get first 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 First value of a group in R 1

 

 

Get First value of each group in R :

Method 1:

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

# Get first value of each group in R

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

dataframe will be

Get First value of a group in R 2

Method 2:

Using group_by() function of dplyr package

# Get first value of each group in R

library(dplyr)
df1 %>% group_by(State) %>% summarise(First_value_sales = first(Sales)) 

dataframe will be

Get First value of a group in R 2b

 

 

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

Method 1:

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

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

first value of dataframe grouped by state and name are

Get First value of a group in R 3

Method 2:

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

library(dplyr)
df1 %>% group_by(State,Name) %>% summarise(First_value_sales = first(Sales)) 

Get First 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.