I have this hypothetical data:
structure(list(ID = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3, 3), A = c(1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0), B = c(0,
0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1), C = c(1, 1, 1, 0,
1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1), M = c(1, 2, 3, 4, 1, 2, 3,
4, 5, 1, 2, 3, 4, 5, 6)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -15L))
I am trying to run a loop that will create a subset based on each value in column M and then create a column in that subset. But I am having trouble with assign()
What I want is to generate a subset M_i for each value of M and then create a column in that subset data M_i$ps_i for a glm prediction. Another issue is not all ID have the same number of M and I'm not sure whether that needs to be considered (and only 1 ID with M=6). I've tried below but can't figure out assign syntax:
n<-max(dat$M)
for (ii in 1:n){
glm<-glm(A~B+C, data=dat,subset=(M==ii)), family=binomial)
M_ii<-subset(dat,M==ii)
assign(paste0("M_",ii, value = M_ii)
M_ii$ps_ii<-predict(glm,type='response')
assign(paste0("ps_ii",ii,value = predict(glm,type='response') )
}