简体   繁体   中英

Removing Column names using like operator in R

I have a dataframe where most of the column names are as below:

tre_ui_1920
tre_ui_2221
tre_ui_8989

and something like

foo_bar_123
foo_bar_456

I want to delete all the columns belonging to foo_bar_* and tre_ui_*

I have seen few codes in R which suggest to use subset and indexing. Is there any better way to do this?

We can use grepl to return a logical index based on the patterns in the column names

i1 <- !grepl("foo_bar_|tre_ui_", names(df1))
subdf1 <- df1[i11]

这很容易在dplyr完成:

dat %>% select(matches("foo_bar_|tre_ui_"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM