Execute dplyr::select with dplyr::across

Viewed 2599

I have a data (df_1):

df_1 <- structure(list(var_1 = c(99.4726192392409, 25.9155194833875), 
var_2 = c(99.9599985964596, 20.3848657943308), var_3 = c(93.1612774543464, 
31.651863809675), var_4 = c(54.2802151478827, 81.9601702317595
), var_5 = c(88.1385736726224, 94.7823309898376), var_6 = c(83.7288120947778, 
72.2155329957604), groups = structure(c(1L, 1L), .Label = c("1", 
"2", "3"), class = "factor")), row.names = c(1L, 10L), class = "data.frame")

I tried:

library(dplyr)

df_1 %>% 
  select_at(.vars = 'var_1')

      var_1
1  99.47262
10 25.91552

It's ok. But:

df_1 %>% 
  select(across(.cols = 'var_1'))

Error: across() must only be used inside dplyr verbs.

How to adjust this last function with select and across?

1 Answers

From the github page for select or across, there is no use case where select is used along with across. According to ?across documentation

across() makes it easy to apply the same transformation to multiple columns, allowing you to use select() semantics inside in summarise() and mutate(). across() supersedes the family of "scoped variants" like summarise_at(), summarise_if(), and summarise_all(). See vignette("colwise") for more details.

It is not mentioned to be used along with select

In the current version, select can take unquoted and quoted variables

library(dplyr)
df_1 %>%
       select('var_1')
#     var_1
#1  99.47262
#10 25.91552

df_1 %>% 
     select('var_1', 'var_2')
#      var_1    var_2
#1  99.47262 99.96000
#10 25.91552 20.38487


df_1 %>% 
      select(var_1, var_2)

Or make use of select_helpers starts_with/ends_with/matches/contains

df1_1 %>% 
      select(starts_with('var'))
#       var_1    var_2
#1  99.47262 99.96000
#10 25.91552 20.38487
Related