Home > OS >  I want to fill NA of this rate column (character class)
I want to fill NA of this rate column (character class)

Time:11-18

I have the data like this:

  rate
1  30%
2  50%
3  NA
4  2.65%
5. NA

And I want to fill NA of this rate column to be the mean of values this total column. Since the rate column is character class. I do not know how to do this: I want the result like this: (30% 50% 2.65%)/3=27.55%

  rate 
1  30%
2  50%
3  27.55%
4  2.65%
5. 27.55%

Since the rate column is character class. I do not know how to do this. Thank you very much!!

CodePudding user response:

I can offer to you this solution, but maybe some pro users of R-tag will advice more elegant answer.

Your data:

df <- data.frame(rate = c("30%", "50%", NA, "2.65%", NA))

Remove our % before calculating mean

library(dplyr)
df1 <- mutate_all(df, function(x) as.numeric(sub("%","",x)))

Replacing NAs to our average value:

df1[is.na(df1)] <- colMeans(df1, na.rm = TRUE)

And result:

df1 %>% 
    mutate(across(everything(), ~paste0(., "%")))

    rate
1    30%
2    50%
3 27.55%
4  2.65%
5 27.55%
  • Related