# [R] replicate and as.matrix: different behaviour between batch and non-batch mode

Oliver Bandel oliver at first.in-berlin.de
Thu Nov 6 14:36:44 CET 2008

```Hello,

for a simulation  I tried the following:

=================================================================
sampmeanvec <- function (from, n, repititions)
{
print( paste("samplesize n:", n, "repititions:", repititions) )
samples.mat <- as.matrix( replicate( repititions, sample(from, n) ) )

# would that case-check be necessary?
#if( n == 1 )
#{
#  samples.mat <- t (samples.mat)
#}

print( "Dim of matrix:")
print( dim(samples.mat) )

meanvec <- apply(samples.mat, 2, mean)
return(meanvec)
}

gleichsamp <- runif(10000)

for( sampsize in c(1,2,4,8,16,32,64,128) )
{
sampmeanvec(gleichsamp, sampsize, 20)
}

=================================================================

The following result:
----------------------
> source("central_limit_theorem.R")
[1] "samplesize n: 1 repititions: 20"
[1] "Dim of matrix:"
[1] 20  1
[1] "samplesize n: 2 repititions: 20"
[1] "Dim of matrix:"
[1]  2 20
[1] "samplesize n: 4 repititions: 20"
[1] "Dim of matrix:"
[1]  4 20
[1] "samplesize n: 8 repititions: 20"
[1] "Dim of matrix:"
[1]  8 20
[1] "samplesize n: 16 repititions: 20"
[1] "Dim of matrix:"
[1] 16 20
[1] "samplesize n: 32 repititions: 20"
[1] "Dim of matrix:"
[1] 32 20
[1] "samplesize n: 64 repititions: 20"
[1] "Dim of matrix:"
[1] 64 20
[1] "samplesize n: 128 repititions: 20"
[1] "Dim of matrix:"
[1] 128  20
>

Look at the first dimension: there the cols and rows are
changed.

I tried directly in the R-shell:

> x <- 1:20
> dim( as.matrix(    replicate(1, sample(x, length(x)) )  ))
[1] 20  1
> dim( as.matrix(    replicate(2, sample(x, length(x)) )  ))
[1] 20  2
> dim( as.matrix(    replicate(3, sample(x, length(x)) )  ))
[1] 20  3
> dim( as.matrix(    replicate(4, sample(x, length(x)) )  ))
[1] 20  4

This looks good (and correct to me).

Can you locate my problem here?

Why is the cols and rows dimensions be changed?

Without using as.matrix the result of replicte is just a vector.
So I have to use it.
But only in the script/batch-mode.

Typed in directly (see above), it works as expected.

Any ideas on this behaviour?

Ciao,
Oliver

```