0

I want to replace NA values in val2 in each row with the mean of val corresponding to that ID column. Any easy (tidyverse) way to do this?

Also, I want to know how to replace it by mean(na.rm=TRUE) of val2 values itself by categories (For ex: for row 6 & 9 val2 will be replace by 4, mean(na.rm=TRUE) of val2 (for ID==c))

For the dataframe in this image :

Image link

R code:

df <- data.frame(ID=c("a","b","c","a","b","c","a","b","c"),
                 val=c(seq(1:9)), val2=c(1,2,4,NA,5,NA,7,NA,NA))
smci
  • 32,567
  • 20
  • 113
  • 146
Vaibhav Singh
  • 1,159
  • 1
  • 10
  • 25

1 Answers1

1

Found the answer myself, incase any answer suggestions which is better than this then please share

df %>% 
group_by(ID) %>% 
mutate(val2 = ifelse(is.na (val2), mean(val), val2))

For Point

df %>% 
group_by(ID) %>% 
mutate(val2 = ifelse(is.na(val2), mean(val2,na.rm=TRUE), val2))
Vaibhav Singh
  • 1,159
  • 1
  • 10
  • 25