I have a tibble, for which I would like to add a prefix to multiple columns in the middle (the tibble in the MRE is just an example the resembles the larger actual tibble).
As these columns are all in a block, I would like to use the dplyr
select(firstcol:lastcol)
notation.
However, when I do this, the column names are not recognized as column names but rather interpreted as objects.
ex.tib <- structure(list(random = c("ABC", "ABC", "ABC", "ABC", "ABC", "ABC"),
foo = c(1, 1, 1, 1, 1, 1),
bar = c(26, 26, 26, 26, 26, 26),
dots = c(4, 3, 3, 4, 4, 4)),
row.names = c(NA,-6L),
class = c("tbl_df", "tbl", "data.frame"))
dplyr::rename_with(ex.tib,
~ paste('demo', .x, sep = '_', recycle0 = T),
.cols = dplyr::select(foo:bar)
)
#> Error in `dplyr::rename_with()`:
#> ! Problem while evaluating `dplyr::select(foo:bar)`.
#> Caused by error:
#> ! object 'foo' not found
Ultimately, the column names should be random demo_foo demo_bar dots
.
If I use another tidy-select selection helper (like everything()
), no error occurs:
dplyr::rename_with(ex.tib,
~ paste('demo', .x, sep = '_', recycle0 = T),
.cols = dplyr::everything()
)
#> # A tibble: 6 × 4
#> demo_random demo_foo demo_bar demo_dots
#> <chr> <dbl> <dbl> <dbl>
#> 1 ABC 1 26 4
#> 2 ABC 1 26 3
#> 3 ABC 1 26 3
#> 4 ABC 1 26 4
#> 5 ABC 1 26 4
#> 6 ABC 1 26 4
What am I doing wrong here so that select(foo:bar)
does not work?
I am running R version 4.3.1 and dplyr 1.1.2.