Reputation: 1
how can i finished this?
Create an "R Function" where the function can be used to replace the missing value of a vector with the mean value of the vector.
Vector with missing value (input):
df <- c(1,2,3,4,5,6,NA,7,8,9,NA)
df
mean_replace <- ...
df <- mean_replace(df) df
The vector after the missing value is replaced with the mean (output):
[1] 1 2 3 4 5 6 5 7 8 9 5
My Answer:
df <- c(1,2,3,4,5,6,NA,7,8,9,NA)
df
mean_replace <- is.na(df)
df <- mean_replace(df)
df
but still failed :
> df <- c(1,2,3,4,5,6,NA,7,8,9,NA)
> df
[1] 1 2 3 4 5 6 NA 7 8 9 NA
> mean_replace <- df(mean)
argument "df1" is missing, with no default
Upvotes: 0
Views: 214
Reputation: 388982
You can use replace
-
df <- c(1,2,3,4,5,6,NA,7,8,9,NA)
mean_replace <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
df <- mean_replace(df)
df
#[1] 1 2 3 4 5 6 5 7 8 9 5
Upvotes: 1
Reputation: 521339
One approach is to assign the mean, with NA
values removed from the input (using na.rm=TRUE
), to any NA
slots in the input vector:
x <- c(1,2,3,4,5,6,NA,7,8,9,NA)
x[is.na(x)] <- mean(x, na.rm=TRUE)
x
[1] 1 2 3 4 5 6 5 7 8 9 5
Upvotes: 0