Return all Column Names that End with a Specified Character using regular expressions in R

With the R functions grep() and names(), you can identify the columns of a matrix that meet some specified criteria.

Say we have the following matrix,

x<-data.frame(v1=c(1,2,3,4),v2=c(11,22,33,44),w1=c(1,2,3,4),w2=c(11,22,33,44))

Screen Shot 2012-12-23 at 5.19.37 PM

To return only those columns that end with a character (e.g., the number 1) submit the R command grep(pattern=".[1]",x=names(x),value=TRUE) into the console. 

Screen Shot 2012-12-23 at 5.19.28 PM

Parse all Numbers from a String using regular expressions in R

The following command replaces all non-digit characters in a string with empty values. The remaining characters, a string of digits, is returned.

gsub(pattern="[^0-9]",replacement="",x=c("Manhattan, KS 66502"))

Screen Shot 2012-12-23 at 5.26.44 PM

gsub(pattern="[^0-9]",replacement="",x=c("M1a2n3h4a5t6t7a8n9, KS 66502"))

Screen Shot 2012-12-23 at 5.28.06 PM