r语言 - 在dplyr中使用tidyselect中的everything()来最后选择一个变量



我想通过编程告诉我想要显示的列LAST. 来自tidyr的函数everything()用作最后一个参数时非常好——您在它之前指定所有内容,并让它完成其余的

但是如果我想用另一种方式来做呢——说我想要哪个变量last,然后让everything()(或其他函数)提供之前未选择的所有变量。

假设在下面的例子中,我想选择cyl作为最后一个变量来显示…

library(tidyverse)
data = mtcars %>% as_tibble() %>% select(1:4)
data %>% select( cyl,everything()) #works -- cyl at beginning
#> # A tibble: 32 × 4
#>      cyl   mpg  disp    hp
#>    <dbl> <dbl> <dbl> <dbl>
#>  1     6  21    160    110
#>  2     6  21    160    110
#>  3     4  22.8  108     93
#>  4     6  21.4  258    110
#>  5     8  18.7  360    175
#>  6     6  18.1  225    105
#>  7     8  14.3  360    245
#>  8     4  24.4  147.    62
#>  9     4  22.8  141.    95
#> 10     6  19.2  168.   123
#> # … with 22 more rows
data %>% select(everything(), cyl) #does not work! -- cyl not at end!
#> # A tibble: 32 × 4
#>      mpg   cyl  disp    hp
#>    <dbl> <dbl> <dbl> <dbl>
#>  1  21       6  160    110
#>  2  21       6  160    110
#>  3  22.8     4  108     93
#>  4  21.4     6  258    110
#>  5  18.7     8  360    175
#>  6  18.1     6  225    105
#>  7  14.3     8  360    245
#>  8  24.4     4  147.    62
#>  9  22.8     4  141.    95
#> 10  19.2     6  168.   123
#> # … with 22 more rows

由reprex包(v2.0.1)创建于2022-07-19

我想让它看起来像这样


data %>% some_fxn() 
# A tibble: 32 × 4
mpg  disp    hp   cyl
<dbl> <dbl> <dbl> <dbl>
1  21    160    110     6
2  21    160    110     6
3  22.8  108     93     4
4  21.4  258    110     6
5  18.7  360    175     8
6  18.1  225    105     6
7  14.3  360    245     8
8  24.4  147.    62     4
9  22.8  141.    95     4
10  19.2  168.   123     6
# … with 22 more rows

是否有另一个功能或选项everything()允许它这样做?

您可以使用relocate()动词

data %>% 
relocate(cyl, .after = last_col())

如果您要经常将内容移到data.frame的末尾,您可以编写自己的helper

relocate_end <- function(..., .after=NULL) {
relocate(..., .after=last_col())
}

,这也适用于多列

data %>% relocate_end(cyl, mpg)
#    disp    hp   cyl   mpg
#    <dbl> <dbl> <dbl> <dbl>
#  1  160    110     6  21  
#  2  160    110     6  21  
#  3  108     93     4  22.8
#  4  258    110     6  21.4
#  5  360    175     8  18.7
#  6  225    105     6  18.1
#  7  360    245     8  14.3
#  8  147.    62     4  24.4
#  9  141.    95     4  22.8
# 10  168.   123     6  19.2

要获得cyl以外的所有内容,只需使用-cyl

data %>% select(-cyl, cyl)
#> # A tibble: 32 x 4
#>      mpg  disp    hp   cyl
#>    <dbl> <dbl> <dbl> <dbl>
#>  1  21    160    110     6
#>  2  21    160    110     6
#>  3  22.8  108     93     4
#>  4  21.4  258    110     6
#>  5  18.7  360    175     8
#>  6  18.1  225    105     6
#>  7  14.3  360    245     8
#>  8  24.4  147.    62     4
#>  9  22.8  141.    95     4
#> 10  19.2  168.   123     6
#> # ... with 22 more rows

你可以试试

data %>% select(setdiff(colnames(data) , "cyl") , cyl)

最新更新