Looping through columns in R

2019-08-15 01:19发布

问题:

I am trying to run a linear regression on each variable relative to x x y1 y2 y3

This is the code i am using

gen <-read.table("CH0032_time_soma.out",sep = "\t",header=TRUE)
dat<-gen[,c(1,3:1131)]

dat_y<-(dat[,c(2:1130)])
dat_x<-(dat[,c(1)])

for(i in names(dat_y)){

model = lm(i~dat_x,dat)
}

I keep getting this error

Error in model.frame.default(formula = i ~ dat_x, data = dat, drop.unused.levels = TRUE) : 
  invalid type (list) for variable 'dat_x'
Calls: lm -> eval -> eval -> <Anonymous> -> model.frame.default
Execution halted

I am all out of ideas to try to resolve this does anyone have any ideas how to resolve this?

Thanks

回答1:

To answer this we must answer in some form: "When are R names not an R name?" The answer is: "when they come from the names-function." The results of the names-function are not R names, are rather R character vectors. That tilde in the first argument to lm is actually building an R formula-object which has in its simplest form one or two R names (also called symbols). Formulas and names/symbols are "language objects" while numbers and character vectors are not. (They are literals, their values are themselves.) You either need to build a formula outside the lm call with as.formula or you need to deliver the columns in a manner that the lm function can match the R names to the data that they point to.

dat_y<-(dat[,c(2:1130)])
dat_x<-(dat[,c(1)])
models <- list()
#
for(i in names(dat_y)){
      y <- dat_y[i]
     model[[i]] = lm( y~dat_x )
    }