Slight correction to David's answer. See inline below.
On 2012-03-17 11:49, David Winsemius wrote:
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.
Actually, ifelse() as used in the OP's code, returns a matrix
(of dimensions equal to those of matrx). It's still not the
correct thing to use, of course.
In addition, for what it's worth, the warning generated by rtriang()
is due to setting the argument 'mode' equal to matrx which I
surmise the OP thought would simply be a single value (1 or 2 in
the example) when in fact it's still the whole matrix, presumably
coerced to a vector. Thus rtriang() will be fed values of 'mode'
that lie outside the interval [min, max] which I'm guessing causes
the warning.
Peter Ehlers
> 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
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.