Replace NA with group average in R
Hello friends! today we’ll be learning how to replace NA with group average in R.
Data
RegionTyPe | SalesRep | Sales |
City1 | A1 | 3 |
City1 | A1 | |
City1 | A1 | 4 |
City1 | A2 | 1 |
City1 | A2 | |
City1 | A2 | |
City1 | A3 | |
City1 | A3 | |
City1 | A3 | |
City2 | A3 | |
City3 | A3 | |
City4 | A3 | |
City5 | A3 | |
City6 | A3 | |
City7 | A3 | |
City8 | A4 | 3 |
City9 | A4 | 3 |
State1 | A4 | 3 |
State2 | A4 | 3 |
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))