在 R 的 lm() 函数的某些部分中使用字符变量向量

Using Vector of Character Variables within certain Part of the lm() Function of R

我正在 R 中执行回归分析,如下所示:

lm_carclass_mod <- lm(log(count_faves+1)~log(views+1)+dateadded+group_url+license+log(precontext.nextphoto.views+1)+log(precontext.prevphoto.views+1)+log(oid.Bridge+1)+log(oid.Face+1)+log(oid.Quail+1)+log(oid.Sky+1)+log(oid.Car+1)+log(oid.Auditorium+1)+log(oid.Font+1)+log(oid.Lane+1)+log(oid.Bmw+1)+log(oid.Racing+1)+log(oid.Wheel+1),data=flickrcar_wo_country)
confint(lm_carclass_mod,level=0.95)
summary(lm_carclass_mod)

在我的分析过程中,因变量和一些自变量变化很大,这就是为什么我想继续手动插入它们

但是,我正在寻找一种方法来用一个函数替换所有 "oid. ..." 变量。

到目前为止,我已经想出了以下

g <- paste("log(",variables,"+1)", collapse="+")

不幸的是,这在 lm() 函数内部不起作用。像这样的公式也不行:

g <- as.formula(
  paste("log(",variables,"+1)", collapse="+")
  )

向量变量里面有以下元素:

variables <- ("oid.Bridge", "oid.Face", "oid.Quail", "oid.Off-roading", "oid.Sky", "oid.Car", "oid.Auditorium", "oid.Font", "oid.Lane", "oid.Bmw", "oid.Racing", "oid.Wheel")     

end 中,我的回归模型应该如下所示:

lm_carclass_mod <- lm(log(count_faves+1)~log(views+1)+dateadded+group_url+license+log(precontext.nextphoto.views+1)+log(precontext.prevphoto.views+1)+g,data=flickrcar_wo_country)
confint(lm_carclass_mod,level=0.95)
summary(lm_carclass_mod)

提前感谢您的帮助!

您需要将两个部分都转换为字符串,然后制作公式:

#the manual bit
manual <- "log(count_faves+1)~log(views+1)+dateadded+group_url+license+log(precontext.nextphoto.views+1)+log(precontext.prevphoto.views+1)"

#the variables:
oid_variables <- c("oid.Bridge", "oid.Face", "oid.Quail", "oid.Off-roading", "oid.Sky", "oid.Car", "oid.Auditorium", "oid.Font", "oid.Lane", "oid.Bmw", "oid.Racing", "oid.Wheel")     

#paste them together 
g <- paste("log(", oid_variables, "+1)", collapse="+")

#make the formula
myformula <- as.formula(paste(manual, '+', g))

然后将公式添加到lm:

lm_carclass_mod <- lm(myformula, data=flickrcar_wo_country