[R] locate the needed columns

Weidong Gu anopheles123 at gmail.com
Tue Aug 30 21:53:34 CEST 2011


If the pattern is characterized by capital letters as your sample
suggests. The following code may help

df<-list()
names(d) = c("A.x", "B.x", "C.x", "A.y", "B.y", "C.y")
group.v<-matrix(NA,nrow=3,ncol=2) ### you may need to modify nrow and ncol
for (i in 1:3) {
group.v[i,]<-names(d)[grep(LETTERS[i],names(d))]
df[i]<-d[,names(d)%in% group.v[i]]
}


Weidong Gu

On Tue, Aug 30, 2011 at 2:31 PM, Hui Du <Hui.Du at dataventures.com> wrote:
>
> Hi All,
>
>                I have a data frame, whose colnames like "A.x, B.x, C.x, A.y, B.y, C.y". There could be many columns like this pattern. I want to compare data in columns A.x with A.y, B.x with B.y and C.x with C.y etc.
> Suppose my data frame is d,
> names(d) = c("A.x", "B.x", "C.x", "A.y", "B.y", "C.y");
>
> If I want to
> D1 = data.frame(d$A.x, d$A.y);
> D2 = data.frame(d$B.x, d$B.y); etc. or do other operation for each pair,
>
>
> What is elegant way to do it rather than use a loop?
>
> Thanks.
>
> HXD
>
>
>        [[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.
>



More information about the R-help mailing list