[R] rtriang using ifelse statement

David Winsemius dwinsemius at comcast.net
Sat Mar 17 19:49:45 CET 2012


On Mar 17, 2012, at 2:36 PM, Diann Prosser wrote:

> Hi All,
>
> I want to draw samples (n=4)  from one of 2 triangular distributions  
> for
> each value in a matrix. I am using an ifelse statement to try to  
> define
> which distribution to draw from.
>
>> From the output, I can see that the ifelse statement is choosing  
>> the correct
> distribution, however, my n=4 simulations aren't occurring. Is there  
> a way
> to adjust the ifelse statement to fix this, or must I take an entirely
> different approach? Many thanks for your help.
>
>> matrx <- matrix(c(2, 1, 1, 2, 2,1), nc=nx)
>> matrx
>     [,1] [,2] [,3]
> [1,]    2    1    2
> [2,]    1    2    1
>> # rtriang from mc2d package: function (n, min = -1, mode = 0, max =  
>> 1)
>> * dmatrx<- ifelse(matrx==1, rtriang(4, min=0.001, mode=matrx,  
>> max=2.001),
> rtriang(4, min=2, mode=matrx, max=3))*
> Warning message:
> In rtriang(4, min = 2, mode = matrx, max = 3) : NaN in rtriang
>> dmatrx
>          [,1]     [,2]      [,3]
> [1,] 2.7627761 1.305099 2.7627761
> [2,] 0.6158242 2.218274 0.6158242
> #(this output should have 4 times as many elements)

If you want four elements then ifelse is the wrong function. It  
returns a _vector_, not a matrix. If you want a 2 * 3 * 4 array then  
you need to use functions appropriate to the purpose. You didn't  
provide 'rtriang', but that's not the issue and this illustrates one  
approach.

 > sapply(matrx,  function(x) if( x==1){rnorm(4)} else {rnorm(4)})
            [,1]       [,2]       [,3]       [,4]       [,5]
[1,] -0.8829560 -0.1173966 -1.3558024  0.2699102 -0.1267338
[2,] -1.5167439  1.2650024  0.2373172 -1.5316328 -1.8418345
[3,] -0.1196694  0.8097693 -0.4223064  0.1053030  0.9030908
[4,] -1.0486071 -0.2470492 -0.5942510 -0.6877101  0.7017433
            [,6]
[1,] -0.5026799
[2,] -4.0098848
[3,] -2.4630189
[4,] -0.6529206
-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list