[R] problem in for loop

Sarah Goslee sarah.goslee at gmail.com
Thu Feb 24 18:45:00 CET 2011


You've fallen afoul of rounding error, FAQ 7.31 I believe,

> rnorm(3, 0, 1)
[1] -2.0903756 -0.9314351  0.1477768

but

> rnorm(mone, 0, 1)
[1] -0.8695359 -0.5429294

because mone is not actually three, but on my linux system a bit less.

> mone == 3
[1] FALSE

> mone < 3
[1] TRUE

You could try
> rnorm(round(mone), 0, 1)
[1] -1.1668325 -0.1606379 -0.4542331

Sarah

On Thu, Feb 24, 2011 at 12:31 PM, li li <hannah.hlx at gmail.com> wrote:
> Hi all.
>   I was having some trouble with a for loop and I found the problem is the
> following.
>   Does anyone have some idea why I got the following R result? Since mone
> is equal to 3, why
> mu1 only have 2 components?
>
>
> library(MASS)
>> p0 <- seq(0.1, 0.9,by=0.1)
>> m <- 10
>>
>>
>> p0 <- p0[7]
>>
>> ## data generation
>>
>> mzero <- p0*m
>> mone <- m-mzero
>> mu1 <- rnorm(mone, 0,1)
>> mu <- c(rep(0,mzero), mu1)
>>
>> var <- diag(m)
>> zv <- mvrnorm(n, mu, var)
> Error in mvrnorm(n, mu, var) : incompatible arguments
>> mone
> [1] 3
>> mu1
> [1] -0.08802108  0.77904786

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list