Re: [R] How to choose columns in data.frame by parts of columns' names?

From: Peter Alspach <PAlspach_at_hortresearch.co.nz>
Date: Wed 31 May 2006 - 11:45:37 EST

Wei-wei

> I have a data.frame which has names as following.
> [1] "XG1" "YG1" "XEST" "YEST"
> [2] "XNOEMP1" "XNOEMP2" "YNOEMP1" "YNOEMP2"
> [3] "XBUS10" "XBUS10A" "XBUS10B" "XBUS10C"
> [4] "YBUS10" "YBUS10A" "YBUS10B" "YBUS10C"
> [5] "XOWNBUS" "XSELFEST" "YOWNBUS" "YSELFEST"
>
> Those columns have names beginning with "X" or "Y". Each "X"
> is paired by a "Y", e.g. "XG1" and "YG1", but they are not in
> the order of "X Y X Y ...". I want to combine "X*" and "Y*" like this:
>
> data.new[,"G1"] <- (data.old[,"XG1"] + endata.use[,"YG1"])/2
>
> How to choose columns by parts of names? For example, I can pick out
> XG1 and YG1 because they have the common part "G1".

Not entirely sure what you mean but one approach might be to re-order the columns so that they are in order.

yourNames

 [1] "XG1"      "YG1"      "XEST"     "YEST"     "XNOEMP1"  "XNOEMP2"
 [7] "YNOEMP1"  "YNOEMP2"  "XBUS10"   "XBUS10A"  "XBUS10B"  "XBUS10C"
[13] "YBUS10"   "YBUS10A"  "YBUS10B"  "YBUS10C"  "XOWNBUS"  "XSELFEST"
[19] "YOWNBUS"  "YSELFEST"

yourNames[order(substring(yourNames,2), substring(yourNames, 1,1))]
 [1] "XBUS10"   "YBUS10"   "XBUS10A"  "YBUS10A"  "XBUS10B"  "YBUS10B"
 [7] "XBUS10C"  "YBUS10C"  "XEST"     "YEST"     "XG1"      "YG1"    
[13] "XNOEMP1"  "YNOEMP1"  "XNOEMP2"  "YNOEMP2"  "XOWNBUS"  "YOWNBUS"
[19] "XSELFEST" "YSELFEST"

gives an idea of what I mean .......

Peter Alspach


The contents of this e-mail are privileged and/or confidenti...{{dropped}}



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed May 31 11:56:49 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 31 May 2006 - 14:10:51 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.