| X1 | X2 | Y1 |
|---|---|---|
| A1 | C1 | E1 |
| A2 | C2 | E2 |
| B1 | D1 | F1 |
| B2 | D2 | F2 |
Note to self: column selection and row filtering in dplyr
notes to self
dplyr
R
As I’m no longer quite the spring chicken I once was, and information seems to be harder to get to stick in the brain, here’s the first in a series of small notes to myself (and anyone else for whom they might be useful) of things that I repeatedly have to look up.
If I have a data frame in R:
and I want to select columns whose name begins with a string, the syntax is:
df %>% dplyr::select(dplyr::starts_with("X"))| X1 | X2 |
|---|---|
| A1 | C1 |
| A2 | C2 |
| B1 | D1 |
| B2 | D2 |
But if I want to filter to include only rows whose value (in a particular column) starts with a certain string, then I can use the stringr package:
df %>% dplyr::filter(stringr::str_starts(X1, "A"))| X1 | X2 | Y1 |
|---|---|---|
| A1 | C1 | E1 |
| A2 | C2 | E2 |