Search code examples
rregressionformulalm

Formula in R not updating properly in loop


So in the following I do not get the proper formula out as expected

f <- dat[,1] ~ 1
for (j in 3:4) {
  f <- update(f, . ~ . + dat[,j] )
}

in only outputs dat[, 1] ~ dat[, j], where dat is a dataframe 1000x4. The output i need is dat[,1] ~ 1 + dat[,3] + dat[,4]


Solution

  • A solution could be :

    f <- dat[,1] ~ 1
    for (j in 3:4) {
      f <- update(f, paste("~ . + dat[,",j,"]",sep="") )