如何重复一个过程N次? [英] How to repeat a process N times?

查看:113
本文介绍了如何重复一个过程N次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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

我需要重复所有这100次,以具有不同的系数并计算偏差,然后将每个偏差的均值放在文本文件中.

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.

我不知道如何实现有关repeat{if()break;}的知识,但是我该怎么做呢?我尝试了循环,但没有成功.

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.

推荐答案

我倾向于这样做.

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)将列表元素逐个应用于"函数;例如它会为列表中的每个元素调用一次函数,然后将结果组装到一个矩阵中.因此,这里get.bias(...)将被调用100次,并且每次返回的结果将被组装成一个矩阵.该矩阵的每个结果都有一个,但是我们希望结果在行中的每个参数都带有一列,因此我们用t(...)进行转置.

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(...).

这篇关于如何重复一个过程N次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆