How to drop columns by name pattern in R?
r
Solution
I found a simple answer using `dplyr`/`tidyverse`. If your `colnames` contain "This", then all variables containing "This" will be dropped.
library(dplyr)
df_new <- df %>% select(-contains("This"))
Problem
I have this dataframe: ``` state county city region mmatrix X1 X2 X3 A1 A2 A3 B1 B2 B3 C1 C2 C3 1 1 1 1 111010 1 0 0 2 20 200 Push 8 12 NA NA NA 1 2 1 1 111010 1 0 0 4 NA 400 Shove 9 NA ``` Now I want to exclude columns whose names end with a certain string, say "1" (i.e. A1 and B1). I wrote this code: ``` df_redacted <- df[, -grep("\\1$", colnames(df))] ``` However, this seems to delete every column. How can I modify the code so that it only deletes the columns that matches the pattern (i.e. ends with "3" or any other string)? The solution has to be able to handle a dataframe with has both numerical and categorical values.