To remove columns in a data frame based on a pattern inside the column names, we can use grep()
and subset()
functions in R.
main.r468 chars13 lines
In this example, we want to remove columns that contain "_2020" or "_555" in their names. First, grep()
function is used to find the column names that match the pattern. Then the subset()
function is used to create a new data frame which excludes the unwanted columns using the -
sign. Finally, we can check the new data frame with the df_new
command.
gistlibby LogSnag