如何在R中循环函数的结果?

时间:2014-03-27 16:56:40

标签: r function loops

假设我有这样的功能:

f<-function(y,x){
    out<-predict(glm(y~x,family="binomial"),type="response")
    new.y<-ifelse(out>=0.5,1,0)
    return(new.y)
}

set.seed(123)   
y0<-rbinom(100,1,0.3)
x<-rnorm(100)

y1<-f(y0,x)
y2<-f(y1,x)
y3<-f(y2,x)
y4<-f(y3,x)
...
ym<-f(ym-1,x)
...

对于给定的m=4,如何循环所需的结果,如:

y<-cbind(y0,y1,y2,y3,y4)
head(y)
  y0 y1 y2 y3 y4
1  0  0  0  0  0
2  1  0  0  0  0
3  0  0  0  0  0
4  1  0  0  0  0
5  1  0  0  0  0
6  0  0  0  0  0
...

1 个答案:

答案 0 :(得分:2)

由于每个y值取决于之前的值,我认为您可以在此处使用for循环:

# Setup initial data
m <- 4
ys <- vector("list", m+1)
set.seed(123)
ys[[1]] <- rbinom(100,1,0.3)
x <- rnorm(100)

# Build y
for (i in 1:m) {
    ys[[i+1]] <- f(ys[[i]], x)
}
y <- do.call(cbind, ys)
colnames(y) <- paste0("y", 0:m)
head(y)
#   y0 y1 y2 y3 y4
# 1  0  0  0  0  0
# 2  1  0  0  0  0
# 3  0  0  0  0  0
# 4  1  0  0  0  0
# 5  1  0  0  0  0
# 6  0  0  0  0  0