# [R] Using loop for a random vector (Montecarlo method)

mlell08 mlell08 at gmail.com
Tue Jan 29 22:31:28 CET 2013

```On 29.01.2013 13:10, mary wrote:
>
> Hi,
> I've understand how to do a permutation matrix but how I can utilize it?
> I would like to have a sample of 5 unit with rotation parameters! The same
> with 10 unit or 20 unit...

You could rewrite your tab function that is accepts a list with named
entries according to the names of your parameters.

So if you've got a parameter matrix which looks like this:
Matrix m:
N, n, E, L, a
0, 0, 0, 0, 0
0, 0, 0, 0, 1
0, 0, 0, 0, 2
0, 0, 0, 1, 0,
...etc.

you first add 1 to each entrey:
m <- m + 1

then, you get a vector of indeices, i.e m[4,] would yield
1, 1, 1, 2, 1   (remember 1 hst been added to each index)

You can write a function which extracts the parameters from the list

# This assumes you have a parameter list which looks like this:
# l: list(n = c(5, 10, 20),
#         a = c(0.1, 0.2, 0.3),
#         E = c(5,10),
#         L = c(0.01, 0.025, 1))  etc...
#
#
# indVec:c(n= 1, a=1, E=2, L=1)
# The function selects the approproate sub-list by the name
getParam <- function(indexVec,l){
n <- names(indexVec)    # get parameter names
ret <- c()        # create list to contain the parameter values
for (i in 1:length(indVec)){
para <- l[[ n[i] ]]    # get the right parameter
# and choose the value specified by indexVec
#Append the value to the list to be returned
ret <- c(ret, para[ indVec[i] ])
}
return(ret)
}

l <- list(n = c(5,10,20), a=c(0.1,0.2,0.3), E=c(5,10),L=c(.01, .025, 1))

r<-t(sapply(1:tl-1,permPar,li=l)) +1

getParam(r[1,],l)
## [1] 5.00 0.10 5.00 0.0

Hope this helps,
Moritz

--
GnuPG Key: 0x7340821E

```