假设我有这样的功能:
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
...
答案 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