replace 0 value to the rows mean in R

Viewed 46

I want to convert rows that have 0.00 value into the mean value of the row. I tried this method but cannot work:

m <- mean(ms$SalaryInUSD)

ms$SalaryInUSD <- replace(ms$SalaryInUSD,ms$SalaryInUSD==0,m)
2 Answers

You can use the following code which calculates the rowMeans excluding the zeros:

df <- data.frame(v1 = c(1,2,3),
                 v2 = c(0,1,2),
                 v3 = c(3,0,2),
                 v4 = c(1,2,0))

df
#>   v1 v2 v3 v4
#> 1  1  0  3  1
#> 2  2  1  0  2
#> 3  3  2  2  0
((df==0)*rowMeans(replace(df, df==0, NA), na.rm=TRUE)[row(df)] + replace(df, df==0, 0))
#>   v1       v2       v3       v4
#> 1  1 1.666667 3.000000 1.000000
#> 2  2 1.000000 1.666667 2.000000
#> 3  3 2.000000 2.000000 2.333333

Created on 2022-07-18 by the reprex package (v2.0.1)

Here is a dplyr solution:

df %>% 
  mutate(row_mean = rowMeans(.[,1:4]),
         across(, ~ifelse(. == 0, row_mean, .))) %>% 
  select(-row_mean)
 v1   v2   v3   v4
1  1 1.25 3.00 1.00
2  2 1.00 1.25 2.00
3  3 2.00 2.00 1.75
Related