Looping through columns in R

自作多情 提交于 2020-01-06 03:26:34

问题


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


来源:https://stackoverflow.com/questions/29425246/looping-through-columns-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!