17.5 Use grep and regular expressions to retrieve columns by their names

Example of a data frame:

# Build data frame
df_regex <- data.frame(expression1=1:4, 
    expression2=2:5, 
    expression3=4:7, 
    annotation=LETTERS[1:4], 
    expression4=6:3, 
    average_expression=c(3.25, 3.75, 4.25, 4.75),
    stringsAsFactors=FALSE)

# Select column names that start with "expression"
grep(pattern="^expression", 
    x=colnames(df_regex))

# Select columns from df_regex if their names start with "expression"
df_regex[, grep(pattern="^expression", colnames(df_regex))]