[R] Using loop for a random vector (Montecarlo method)
mlell08
mlell08 at gmail.com
Mon Jan 28 14:10:24 CET 2013
On 28.01.2013 12:06, mary wrote:
> Hi,
>
> I would like to replicate a sort of Montecarlo experiment:
>
> I have to generate a random variable N(0,1) with 100 observations but I have
> to contaminate this values at certain point in order to obtain different
> vectors with different samples:
Hi,
tab<-function(N,n,E,L,a){
for(i in 1:100){
X1<-rnorm(N*(1-a),0,1)
X2<-rnorm(N*(a),E,L)
X_tab<-sample(c(X1,X2),n,replace=T)
}
return(X_tab)
}
l <- list(n = c(5,10,20), a=c(0.1,0.2,0.3), E=c(5,10),L=c(.01, .025, 1))
# translate permutation number in indices for rotating numbers, like in
# a code lock for a bike
# n a E L
# i.e. Permutation #0: 0,0,0,0
# #1: 0,0,0,1
# #2: 0,0,0,2
# #3: 0,0,1,0
# #4: 0,0,1,1
# Note these indices start at 0 for the sake of easier calculation.
# you have to add +1 manually,
# then you get i.e. for permutation #4: n[1], a[1], E[2], L[2]
# n is the permutation number, li is a 'list' with your parameters (l)
permPar <- function(n,li)
{
lengths<-sapply(li,length)
len.l <- length(lengths)
len.l
ind <- rep(0,len.l)
names(ind) <- names(li)
for(i in seq(len.l,1,-1)){
ind[i] <- n %% lengths[i]
n <- n %/% lengths[i]
if(n==0) break
}
if(n>0) stop("Index too big")
return(ind)
}
# Number of possible permutations:
tl <- 1
for (i in 1:length(l)){
tl <- tl*length(l[[i]])
}
# for each possible permutation:
# execute permPar(<counting index>,li=l)
# and swap columns and rows of the resulting matrix
t(
sapply(1:tl-1, permPar, li=l)
)
this table od parameter indices can be used for acessing the parameters
in the list l
Good Luck,
Moritz
--
GnuPG Key: 0x7340821E
More information about the R-help
mailing list