How do I select variables in an R whose names contain a particular string?

Viewed 50

I have a large data set with thousands of columns. The column names include various unwanted characters as follows:

col1*
col2*
col3*[Note]

I would like to remove all character strings starting with * and with *[Note] from all column names to be left with clean:

col1 col2 col3 What is the most efficient way to do this for 5000+ columns?

2 Answers

We could use sub from base R

names(df1) <- sub("\\*.*", "", names(df1))

A dplyr solution

library(dplyr)
library(stringr)
df1 %>%
  rename_with(~str_remove(string = ., pattern = "\\*.*"), everything())
Related