I am get an error when I try to add a second row with NA's in the Age column of the DF and run the code to clean it up. I am wondering how to fix it. I am new to R and this example comes from a Udemy Course. This is not a quiz question - it is part of the presentation.
I added the additional row because I wanted to see if the code would work.
I did search this forum, but could not find an answer I understand.
#create the df cols
Country <- c("France", "Spain", "Germany", "Spain", "Germany", "France", "Spain", "France","Germany", "France")
Age <- c(44, 27, 30, 38, 40, 35, NA, 48, 50, 37)
Salary <- c(72000, 48000, 54000, 61000, NA, 58000, 52000, 79000, 830000, 67000)
Purchased <- c("No","Yes","No","No","Yes","Yes","No","Yes","No","Yes")
#create the df
empdata <- data.frame(Country, Age, Salary, Purchased)
#The logic to set the 'NA' values to the mean will not work when you add this record, WHY?
empdata[nrow(empdata) + 1, ] = c('Spain', NA , 67000.00, "Yes")
#Run this logic to fix the 'NA' Values
empdata$Age = ifelse(is.na(empdata$Age),
ave(empdata$Age, FUN = function(x) mean(x, na.rm= TRUE)),
empdata$Age)
empdata$Salary = ifelse(is.na(empdata$Salary),
ave(empdata$Salary, FUN = function(x) mean(x, na.rm = TRUE)),
empdata$Salary)
#view the data
empdata