How to write a custom function which will replace all the missing values in a vector with the mean of values in R?

0 votes
I want to write a custom function which will replace all missing values in a vector with the calculated mean values in R
Jul 4, 2018 in Data Analytics by DataKing99
• 8,130 points
163 views

1 answer to this question.

0 votes

Consider this vector:

a<-c(1,2,3,NA,4,5,NA,NA)

Write the function to impute the values:

mean_impute<-function(x){
ifelse(is.na(x),mean(x,na.rm = T),x)
}

The result would be as follows:

mean_impute(a)
1 2 3 3 4 5 3 3
answered Jul 4, 2018 by CodingByHeart77
• 3,690 points

Related Questions In Data Analytics

+1 vote
2 answers

Custom Function to replace missing values in a vector with the mean of values

Try this. lapply(a,function(x){ifelse(is.na(x),mean(a,na.rm = TRUE) ...READ MORE

answered Aug 14 in Data Analytics by anonymous
85 views
0 votes
2 answers

How to count the number of elements with the values in a vector?

Use dplyr function group_by(). > n = as.data.frame(num) > ...READ MORE

answered Aug 21 in Data Analytics by anonymous
• 28,040 points
118 views
0 votes
1 answer

How to replace all occurrences of a character in a character column in a data frame in R

If you used sub() to replace the ...READ MORE

answered Jun 28 in Data Analytics by anonymous
• 28,040 points
57 views
0 votes
1 answer

How to replace only set of values in a vector to different values in a dataframe?

If you have a condition using which ...READ MORE

answered Aug 19 in Data Analytics by anonymous
• 28,040 points
18 views
0 votes
1 answer

How to replace a value in a data frame based on a conditional 'If' statement?

It's easier to convert alpha to characters ...READ MORE

answered Jun 6, 2018 in Data Analytics by darklord
• 6,170 points
70 views
0 votes
1 answer

How to calculate group mean and assign it to new data in R

You can use something like this: df$grp.mean.values <- ...READ MORE

answered Jun 27, 2018 in Data Analytics by darklord
• 6,170 points
51 views
0 votes
1 answer

Mean of one column with respect to another

Consider the inbuilt iris dataset in R. Use ...READ MORE

answered Jul 25, 2018 in Data Analytics by CodingByHeart77
• 3,690 points
32 views
0 votes
1 answer

Big Data transformations with R

Dear Koushik, Hope you are doing great. You can ...READ MORE

answered Dec 17, 2017 in Data Analytics by Sudhir
• 1,610 points
49 views
0 votes
1 answer

How to replace NA values in a dataframe with Zero's ?

It is simple and easy: df1<-as.data.frame(matrix(sample(c(NA, 1:10), 100, ...READ MORE

answered Apr 10, 2018 in Data Analytics by CodingByHeart77
• 3,690 points
129 views
0 votes
1 answer

How to create dummy variables based on a categorical variable of lists in R?

You can use mtabulate in the following way: library(qdapTools) cbind(data[1], ...READ MORE

answered Apr 13, 2018 in Data Analytics by CodingByHeart77
• 3,690 points
543 views