mina mina - 1 year ago 84
R Question

replace NA by truncated normal distribution values in r

I am trying to replace NAs by truncated normal distribution values.
First I used

as follows and the function worked:

v.new <- replace(vector,v, sample(8,length(v),replace =FALSE))

However when I try to use
it seems not to work. I got any error messages and it takes ages to replace the NAs by the desired interval. Any suggestion to make this work?


# Some data

# My function
add.trunc.to.NAvector <- function(vector){
v <- NULL
for(i in 1:length(vector)){
v <- append(v, i)
mean.val <- mean(vector)
sd.val <- sd(vector)
min.val <- mean.val - 4 * sd.val
max.val <- mean.val + 4 * sd.val
v.new <- replace(vector,v, rtnorm(length(v), lower = min.val, upper = max.val))


Answer Source

Should not this work?

v <- airquality$Ozone
v.new <- v
indices <- which(is.na(v))
m <- mean(v[-indices])
s <- sd(v[-indices])
v.new[indices] <- rtnorm(length(indices), lower = m-4*s, upper = m+4*s)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download