Bae
Bae

Reputation: 97

Fill NA values with random numbers generated from a specific distribution in R

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?

Upvotes: 0

Views: 531

Answers (2)

Antreas Stefopoulos
Antreas Stefopoulos

Reputation: 282

Another approach could be,

df[is.na(df$id)] <- runif(n = length(which(is.na(df$id))), min = 4,max = 8)

Upvotes: 0

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

Try this

df$id <- ifelse(is.na(df$id) , runif(1,4,8) , df$id)

Upvotes: 0

Related Questions