subset of variable whose names contain pattern in r

One way to subset variables whose names contain a specific pattern in R is to use regular expressions and the select() function from the dplyr package.

For example, let's say you have a data frame named my_data with variables whose names contain the pattern "var". You can use the select() function with the matches() function, which takes a regular expression pattern, to subset the variables you want:

main.r
library(dplyr)

# create example data frame
my_data <- data.frame(var1 = 1:5, var2 = 6:10, xyz = 11:15)

# select variables whose names contain "var"
my_subset <- my_data %>% select(matches("var"))
198 chars
8 lines

In this example, my_subset will contain only the variables "var1" and "var2" from my_data.

You can modify the regular expression pattern as needed to match the specific pattern you are looking for in the variable names.

gistlibby LogSnag