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

David Winsemius dwinsemius at comcast.net
Wed Jul 28 15:21:38 CEST 2010


(Forgot to copy the list.)

Begin forwarded message:

> From: David Winsemius <dwinsemius at comcast.net>
> Date: July 28, 2010 7:44:38 AM EDT
> To: Tony <lulala at gmail.com>
> Subject: Re: [R] How to point a column of dataframe by a "character"
>
>
> On Jul 28, 2010, at 5:35 AM, Tony 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])
>
You could try instead:

model1 <- lm(Y ~ . , data=data[ , i, drop=FALSE])


I added the drop=FALSE to prevent a single column from being converted  
to a nameless vector.

 > testdf <- data.frame(testcol=letters[1:10], stringsAsFactors=FALSE)
 > testdf[,1]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
 > testdf[,1, drop=FALSE]
   testcol
1        a
2        b
3        c
4        d
5        e
6        f
7        g
8        h
9        i
10       j

BTW, "data" as the name for an object is a bad idea. As seen in the  
line above, it means you brain needs to do extra work to keep straight  
the fact that data is now the name for two things, the object and the  
parameter. It could get even more complicated if you used the "data"  
function. Notice that I even numbered the model. I thought the name  
"model" was too non-specific.

David.
>
>> # 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
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list