Search code examples
rdplyrtidyversetidyselect

selecting specific columns using `tidyselect` in `dplyr::filter_at`


This works as expected except for the fact that the column meaningful is also selected. I just want the following columns to be selected:

mean...summary, mean.conf.low...summary, mean.conf.high...summary

How can I do that?

library(tidyverse)

# dataframe
df <- structure(
  list(
    group = structure(1:2, .Label = c("a", "b"), class = "factor"),
    meaningful = c(0.98, 1.39333333333333),
    mean...summary = c(0.98,
                       1.39333333333333),
    n...summary = c(3L, 3L),
    mean.conf.low...summary = c(0.717103575690863,
                                0.921129311562406),
    mean.conf.high...summary = c(1.24289642430914,
                                 1.86553735510426)
  ),
  class = c("tbl_df", "tbl", "data.frame"),
  row.names = c(NA, -2L)
)

# changing few columns
df %>%
  dplyr::mutate_at(
    .tbl = .,
    .vars = dplyr::vars(dplyr::matches("^mean...|^mean.conf")),
    .funs = ~ format(round(x = ., digits = 3), nsmall = 3)
  )
#> # A tibble: 2 x 6
#>   group meaningful mean...summary n...summary mean.conf.low...~ mean.conf.high.~
#>   <fct> <chr>      <chr>                <int> <chr>             <chr>           
#> 1 a     0.980      0.980                    3 0.717             1.243           
#> 2 b     1.393      1.393                    3 0.921             1.866

Created on 2019-11-22 by the reprex package (v0.3.0)


Solution

  • . has a special meaning in regular expressions, so you could skip it and treated as a literal . by using \\, e.g. matches("^mean\\.\\.\\.|^mean\\.conf") or matches("^mean\\.{3}|^mean\\.conf")