1

Suppose I have a function like this:

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

For a given m=4, how to loop a desired result like:

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 Answer 1

2

Since each y value depends on the previous ones, I think you could just use a for loop here:

# 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.