Replace NA with group average in R

Hello friends! today we’ll be learning how to replace NA with group average in R.

Data

RegionTyPeSalesRepSales
City1A13
City1A1
City1A14
City1A21
City1A2
City1A2
City1A3
City1A3
City1A3
City2A3
City3A3
City4A3
City5A3
City6A3
City7A3
City8A43
City9A43
State1A43
State2A43

Code

# replace NA with group average
library(dplyr)
# load file
df <- read.csv("Test.csv")
# Group by SalesRep column and replace NA's in Sales column
df1 <- df %>% group_by(SalesRep) %>% mutate(abc = ifelse(is.na(Sales), mean(Sales, na.rm = T), Sales))

Leave a Reply

Your email address will not be published. Required fields are marked *