Hi guys,

I've to create a variable a in which elements are column names of a database.

For example, I have the following column names of a df:

    colnames(df)
    "PS_01", "PS_01_mod2", "PS_02", "PS_02_mod2"

I want to create a vector a in which elements are the column names of df ending with mod2, so I want to create this situation 

    a <- "PS_01_mod2", "PS_02_mod2"

How can I do this in a simple way?


Hi, a simple `grep()` command will do this for you, and we can add a regular expression ('regex') to ensure positional specificity:

    vector <- c('PS_01', 'PS_01_mod2', 'PS_02', 'PS_02_mod2', 'mod2_mod1')
    idx <- grep('mod2$', vector)
    vector[idx]
    [1] "PS_01_mod2" "PS_02_mod2"

The dollar, `$`, means that we only want '*mod2*' appearing at the end of a line.

Note the difference here, without the dollar:

    idx <- grep('mod2', vector)
    vector[idx]
    [1] "PS_01_mod2" "PS_02_mod2" "mod2_mod1"

Kevin
