[R] How to point a column of dataframe by a "character"

Joshua Wiley jwiley.psych at gmail.com
Wed Jul 28 14:59:07 CEST 2010


Hi Tony,

I am sure there are other ways, but I would create formula objects and
then pass them to lm().  Here's an example:

mydata <- data.frame(Y = 1:10, X1 = 11:20, X2 = 21:30)

my.names <- names(mydata)[-1]

for(i in my.names) {
  my.formula <- formula(paste("Y ~ ", i, sep = ""))
  my.lm <- lm(my.formula, data = mydata)
  print(summary(my.lm))
}

HTH,

Josh

On Wed, Jul 28, 2010 at 2:35 AM, Tony <lulala at gmail.com> wrote:
> Hello,
>
> Here is a dilemma I am having for a long time. But, I couldn't figure it
> out.
> I have an vector of Y and a data frame named "data",which contains all Xs. I
> tried to be more efficient in fitting a simple linear regression with each
> X.
>
>
> Firstly,
> for (i in 1:(dim(data)[2])){
> model<-lm(Y~data[,i])
> # this is not what I want since the name of coefficient will be data[,i]
> # I need coefficient name to be the name for each variable
> # for instance:
> # Coefficients:
>    # (Intercept)    data[, 1]
>    #     24.2780           -0.3381
> }
>
>
> Second try!
> I first create a vector of characters (Xs) that contains possible names of
> X. This vector is exactly the same as colnames of X.
>
> #my Xs
> Xs<-c("a","b","c")
> for (i in length(Xs)){
> model<-lm(Y~data[,Xs[i]])
> # Again, not what I want
> # Coefficients:
>    # (Intercept)    data[, Xs[1]]
>    #     24.2780           -0.3381
> }
>
>
> Thus, how can I solve this dilemma?
> I think about trying to find a function that can map the name of variable to
> values of that variable. That is, I first attach the data. I can type a to
> pull out values of data[,"a"] (a vector of numeric) directly. However, using
> Xs[1] will give me only "character" - "a". Thus, is there any function that
> allow me to pull values of dadta[,"a"] , eg, some_function(Xs[1]) give me
> values of data[,"a"]
>
> Any help is appreciated.
>
>
> Tony
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list