1

Select columns based on prefix in a formula

I am using R.

I have to write a formula of the form: y ~ a + b + c_1 + c_2 + c_3 + d + e | f | c_1 + c_2 + c_3

What's the best way to select all the columns that start with c_ when I have lots of them?

Those columns come from a dataframe, so names(df) retrieves all the possible variables

Submitted September 06th 2021 by Admin

Answers
0

You could use

vec <- names(df)[startsWith(names(df), "c_")]

and then for example use

paste(vec, collapse = "+")
#> [1] "c1+c2+c3"

Admin | 1 month ago



Relevant Questions