grep in R

Sometimes we need to find the indices of columns in a data frame that match a pattern and here comes grep:

v1 <- c(1,2,3)
v2 <- c(3,4,5)
tt2 <- c(5,6,7)
tt3 <- c(9,0,8)
df <- data.frame(v1=v1, v2=v2, tt2=tt2, tt3=tt3)
# suppose you want to find the columns with the pattern "tt"
ttIndices <- grep("tt", colnames(df))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s