对 dplyr 中特定范围的列名进行排序

chi*_*sin 2 r dplyr

我有一个数据框,希望按字母顺序对特定列进行排序dplyr。我知道我可以使用下面的代码对所有列进行排序,但我只想按字母顺序对 C、B 和 A 列进行排序。我尝试使用该across函数,因为我实际上想选择 C:A 列,但这不起作用。

df <- data.frame(1:16)
df$Testinfo1 <- 1
df$Band <- 1
df$Alpha <- 1
df$C <- c(10,12,14,16,10,12,14,16,10,12,14,16,10,12,14,16)
df$B <- c(10,0,0,0,12,12,12,12,0,14,NA_real_,14,16,16,16,16)
df$A <- c(1,1,1,1,1,1,1,1,1,1,1,14,NA_real_,NA_real_,NA_real_,16)
df

df %>% 
  select(sort(names(.)))

     A Alpha  B Band  C Testinfo1 X1.16
 1:  1     1 10    1 10         1     1
 2:  1     1  0    1 12         1     2
 3:  1     1  0    1 14         1     3
 4:  1     1  0    1 16         1     4
 5:  1     1 12    1 10         1     5
 6:  1     1 12    1 12         1     6
 7:  1     1 12    1 14         1     7
 8:  1     1 12    1 16         1     8
 9:  1     1  0    1 10         1     9
10:  1     1 14    1 12         1    10
11:  1     1 NA    1 14         1    11
12: 14     1 14    1 16         1    12
13: NA     1 16    1 10         1    13
14: NA     1 16    1 12         1    14
15: NA     1 16    1 14         1    15
16: 16     1 16    1 16         1    16
Run Code Online (Sandbox Code Playgroud)

我想要的输出如下:

    X1.16 Testinfo1 Band Alpha  A  B  C
 1:     1         1    1     1  1 10 10
 2:     2         1    1     1  1  0 12
 3:     3         1    1     1  1  0 14
 4:     4         1    1     1  1  0 16
 5:     5         1    1     1  1 12 10
 6:     6         1    1     1  1 12 12
 7:     7         1    1     1  1 12 14
 8:     8         1    1     1  1 12 16
 9:     9         1    1     1  1  0 10
10:    10         1    1     1  1 14 12
11:    11         1    1     1  1 NA 14
12:    12         1    1     1 14 14 16
13:    13         1    1     1 NA 16 10
14:    14         1    1     1 NA 16 12
15:    15         1    1     1 NA 16 14
16:    16         1    1     1 16 16 16
Run Code Online (Sandbox Code Playgroud)

H 1*_*H 1 7

您可以使用relocate()(从 dplyr 1.0.0 开始):

library(dplyr)

vars <- c("C", "B", "A")

df %>% 
  relocate(all_of(sort(vars)), .after = last_col())
Run Code Online (Sandbox Code Playgroud)

如果您要传递名称的字符向量,则应该将其包装起来all_of()(如果缺少任何变量,则会出错),否则any_of()不会。