How to repeat a process N times?

10.9k views Asked by At

I have:

x = rnorm(100)
# Partie b
z = rbinom(100,1,0.60)
# Partie c
y = 1.4 + 0.7*x - 0.5*z
# Partie d
x1 = abs(x)
y1 = abs(y)
Don<-cbind(y1,x1,z)

Don1 <- data.frame(Don)
Reg <- glm(y1~x1+z,family=poisson(link="log"),Don1)

# Partie e
#Biais de beta
Reg.cf <- coef(Reg)
biais0 = Reg.cf[1] - 1.4
biais1 = Reg.cf[2] - 0.7
biais2 = Reg.cf[3] + 0.5

And I need to repeat all this 100 times in order to have different coefficient and calculate the bias and then put the mean of each biais in a text file.

I don't know how to implement I taught about repeat{if()break;} But how do I do that? I tried the loop for but it didn't work out.

1

There are 1 answers

0
jlhoward On BEST ANSWER

I'd be inclined to do it this way.

get.bias <- function(i) {  # the argument i is not used
  x <- rnorm(100)
  z <- rbinom(100,1,0.60)
  y <- 1.4 + 0.7*x - 0.5*z
  df <- data.frame(y1=abs(y), x1=abs(x), z)
  coef(glm(y1~x1+z,family=poisson(link="log"),df)) - c(1.4,0.7,-0.5)
}

set.seed(1)   # for reproducible example; you may want to comment out this line  
result <- t(sapply(1:100,get.bias))
head(result)
#      (Intercept)         x1           z
# [1,]   -1.129329 -0.4992925 0.076027012
# [2,]   -1.205608 -0.5642966 0.215998775
# [3,]   -1.089448 -0.5834090 0.081211412
# [4,]   -1.206076 -0.4629789 0.004513795
# [5,]   -1.203938 -0.6980701 0.201001466
# [6,]   -1.366077 -0.5640367 0.452784690

colMeans(result)
# (Intercept)          x1           z 
#  -1.1686845  -0.5787492   0.1242588 

sapply(list,fun) "applies" the list element-wise to the function; e.g. it calls the function once for each element in the list, and assembles the results into a matrix. So here get.bias(...) will be called 100 times and the results returned each time will be assembled into a matrix. This matrix has one column for each result, but we want the results in rows with one column for each parameter, so we transpose with t(...).