Unsure why NA values are not being removed/replaced in my dataset

Viewed 37

I'm trying to delete NAs from a single column and also replace NAs with the median in a group of columns but when I complete the command it is not working, it just prints the entire dataset. There is no error message but the NAs are not removed. I've been stuck at this stage for a day now so any help would be appreciated :) The code I'm using is


#as there is only 1 NA in the month columns we will remove that row so that it does not get replaced with the mean

water3[!is.na(water3$Month),]

#replace NA values with the median on skewed columns


water3 %>% 
  mutate_if(is.numeric, function(x) ifelse(is.na(x), median(x, na.rm = T), x))

1 Answers

As Gregor mentioned in the comment, if you want to permanently change the value of the NA to the median value of the dataset (for your case) then you would always want to use <- when using the chaining operator %>% to save the dataset to the water3 variable.

This way it gets saved and then the next time you call water3 you would be able to get a full dataset with the NAs replaced to the median of the data.

Your code will look like this to work:

water3 <- water3 %>% 
  mutate_if(is.numeric, function(x) ifelse(is.na(x), median(x, na.rm = T), x))

If you want to just see what the dataset might look like or test out a function on a dataset but not necessarily save it then you would want to do it your way which was:

water3 %>% 
  mutate_if(is.numeric, function(x) ifelse(is.na(x), median(x, na.rm = T), x))

I hope this helps.

Related