0
$\begingroup$

A friend of mine has recently started working on R-studio and is interested in filling the NA values in different columns using the above-mentioned function. Also, since he intends to run a time series analysis for every column, what should be the correct approach?

$\endgroup$
2
  • $\begingroup$ I think, the initial decision should be to consider: 1. Is imputation the right thing to do? Sometimes, replacing the missing values does not make sense. 2. If imputation is the right choice, what exactly do you want to achieve: a) replace by column mean, b) replace by row mean c) or replace by the mean of a given user based on other responses they have $\endgroup$
    – Sadiaz
    Nov 23 '19 at 9:42
  • $\begingroup$ I want to replace by the column mean. $\endgroup$ Nov 24 '19 at 11:43
0
$\begingroup$

To replace by column means, an easy approach would be to use the base R function colMeans. Let's say you have a data frame df.

1) If you want to replace the NAs per column one by one, you could try this:

df <- sapply(df, function(x)ifelse(is.na(x), mean(x, na.rm=TRUE), x))

2) If you want to replace all NAs in one go, you could try this:

df <- ifelse(is.na(df), rep(colMeans(df, na.rm=TRUE), rep(nrow(df), ncol(df))), unlist(df))
$\endgroup$

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .