Tag Archives: Grep

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))