13.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))
## [1] 1 2 3 5
# Select columns from df_regex if their names start with "expression"
df_regex[, grep(pattern="^expression", colnames(df_regex))]
## expression1 expression2 expression3 expression4
## 1 1 2 4 6
## 2 2 3 5 5
## 3 3 4 6 4
## 4 4 5 7 3