如何重复一个过程N次?

编程入门 行业动态 更新时间:2024-10-20 07:44:03
本文介绍了如何重复一个过程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次?

本文发布于:2023-11-30 20:51:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!