简体   繁体   中英

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

I am performing a regression analysis within R that looks the following:

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)

The dependent variable as well as some of the independent variables are quite variable throughout my analysis, which is why I would like to keep inserting them manually .

However, I am looking for a way to replace all of the "oid. ..." variables with one single function.

So far I have come up with the following :

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

Unfortuntaley this does not work inside the lm() function. Neither does a formula like this:

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

The vector variables has the following elements in it:

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

In the end my regression model should look something like this:

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)

Thanks for your helpm in advance!

You would need to convert both of the parts into a string and then make the formula:

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

Then you add the formula into lm :

lm_carclass_mod <- lm(myformula, data=flickrcar_wo_country         

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM