Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206553

How to fix incompatible arguments mvrnorm?

$
0
0

So I have to impute data for my Stats course. This works like a charm with the example we did in class. But the second I do it with this data, I get an "incompatible arguments" with the mvrnorm function. This is what my codelooks like:

##Impute Random
random.imp <- function(a){
  missing <- is.na(a)
  n.missing <- sum(missing)
  a.obs <- a[!missing]
  imputed <- a
  imputed[missing] <- sample(a.obs, n.missing, replace=TRUE) 
  return (imputed)
}

impute <- function(a, a.impute){ 
  ifelse(is.na(a), a.impute, a)
}

Attach(Data)

N_bikes.imp <- random.imp (N_bikes) 
humidity.imp <- random.imp (humidity)

rep = 10
for (i in 1:rep){
  # impute N_bikes
  lm_1 = lm(N_bikes ~ humidity.imp +temperature + feels_like + wind_speed + holiday + weekend + season )

  data_temp = data.frame(humidity.imp, temperature, feels_like, wind_speed, holiday, weekend, season)

  N_bikes.imp.1 <- impute(N_bikes, predict(lm_1, data_temp))

  lm_2 = lm(N_bikes.imp.1 ~ humidity.imp + temperature + feels_like + wind_speed + holiday + weekend + season )

  X = model.matrix(lm_2, data=data_temp)

  sigma.hat.square = sum(resid(lm_2)^2)/lm_2$df.residual*X%*%qr.solve(t(X)%*%X)%*%t(X)

  pred1 = mvrnorm(mu = predict(lm_2, data_temp), Sigma = sigma.hat.square)
  N_bikes.imp = impute(N_bikes, pred1)
}

Then I get this kicked back to me:

Error in mvrnorm(mu = round(predict(lm_2, data_temp)), 
Sigma = sigma.hat.square) : 
  incompatible arguments

Any suggestions?


Viewing all articles
Browse latest Browse all 206553

Trending Articles