1

My dataframe consists of:

>car_df

Grade         Speed      Age
  7             54       13
  10            NA       4
  NA            43       23
  3             NA       NA
  1             87       12
  NA            NA       NA

and an example of mean for each each column, ignoring NA is:

 > mean_col

 Grade      Speed      Age
  3.6       30.67      8.67

I'm trying to replace the NA values in the column Grade and Speed with the mean from mean_col.

So the new dataframe would look like:

Grade         Speed      Age
  7             54       13
  10            30.67    4
  3.6           43       23
  3             30.67    NA
  1             87       12
  3.6           30.67    NA

I tried:

car_df$Grade <- replace(is.na, mean_col$Grade)

car_df$Speed <- replace(is.na, mean_col$Speed)

But it wouldn't work. Would appreciate some help on this.

Maxxx
  • 3,688
  • 6
  • 28
  • 55

1 Answers1

0

With tidyr's replace_na you can do:

car_df=data.frame(Grade=c(7,10,NA,3,1,NA),Speed=c(54,NA,43,NA,87,NA),Age=c(13,4,23,NA,12,NA))
library(tidyr)
replace_na(car_df,as.list(colMeans(car_df,na.rm=T)))
Marcus Ritt
  • 477
  • 5
  • 12