Home > Enterprise >  R: Replace all values in column (NA and values) with mean of values
R: Replace all values in column (NA and values) with mean of values

Time:09-23

I have a dataframe with NA's and values in one column:

Day <- 1, 1, 1, 1, 1, 1
Section <- 1, 1, 1, 2, 2, 2
Value <- 1.2, 0.58, NA, 1.1, 0.8, NA

I want to get the mean of Values by Day and Section and replace all the values with it.

Day <- 1, 1, 1, 1, 1, 1
Section <- 1, 1, 1, 2, 2, 2
Value <- 0.89, 0.89, 0.89, 0.95, 0.95, 0.95

I tried but it obviously only adds the mean to the NA spaces. Any help would be appreciated.

mean_value <- df%>%  group_by(Day, Plate) %>%
  mutate(Value = ifelse(is.na(Value), mean(Value , na.rm=TRUE), Value ))

CodePudding user response:

We can just subset the non-NA elements to replace it

library(dplyr)
df %>%
     group_by(Day, Plate) %>%
     mutate(Value = mean(Value[!is.na(Value)]))

Or use the na.rm in mean

df %>%
     group_by(Day, Plate) %>%
     mutate(Value = mean(Value, na.rm = TRUE))
  •  Tags:  
  • r
  • Related