I want to fill NA values with random numbers generated from a specific distribution in R. I have seen some methods to impute NA values with mean, but haven't seen imputing with some numbers generated from a specific distribution.
For example, I have a data df
as follows:
df <- data.frame(id = c(1,1,1,2,2,NA,2,3,NA,5,5,NA,9,9))
Obviously there are some NA values. I want to replace them by numbers generated from a uniform distribution. Let's say I want to impute NA's with numbers from Uniform(4,8).
Is there a easy way to do this?
CodePudding user response:
Try this
df$id <- ifelse(is.na(df$id) , runif(1,4,8) , df$id)