[R] colname refered by a variable

David Winsemius dwinsemius at comcast.net
Fri Dec 3 15:13:05 CET 2010


On Dec 3, 2010, at 4:14 AM, Keith Jewell wrote:

> or even shorter
> df[,paste("A","C",sep="")]

Other grepping methods that generalize better to partial matches:

df[ , grep("^AC$", colnames(df))]

df[ grep("^AC$", colnames(df)) ]

--  
David.
>
>
> "Santosh Srinivas" <santosh.srinivas at gmail.com> wrote in message
> news:AANLkTikcJy7BVyfBwUwmRQ4dHg4pBdau+Qh_7+K+bRt2 at mail.gmail.com...
> try this ..
>
> df[,colnames(df)==paste("A","C",sep="")]
>
> On Fri, Dec 3, 2010 at 12:05 PM, Yuan Jian <jayuan2008 at yahoo.com>  
> wrote:
>> Hello,
>>
>> I tried to use a variable to refer colname, but I got error, could  
>> anyone
>> give me advice?
>>
>>> df=data.frame(cbind(AB=1:3,AC=3:5))
>>> df$AC
>> [1] 3 4 5
>>> df$paste("A","C",sep="")
>> Error: attempt to apply non-function
>>
>> thanks
>> Jian

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list