如何在dplyr中用tidyselect的everything()指定变量最后显示?
解决方案:将指定列移至数据框末尾
在tidyverse生态中,有两种简洁的方法可以实现把指定列放到最后显示的需求:
方法1:使用select()结合负索引
先选择除目标列外的所有列,再单独选择目标列,即可实现将目标列移至末尾:
library(tidyverse) data = mtcars %>% as_tibble() %>% select(1:4) # 将cyl移至末尾的写法1 data %>% select(-cyl, everything(), cyl) # 更简洁的写法2 data %>% select(everything() - cyl, cyl)
方法2:使用relocate()函数(推荐)
relocate()是tidyverse专门用于调整列位置的函数,通过.after = everything()参数可以直接把目标列放到所有列的最后:
data %>% relocate(cyl, .after = everything())
为什么select(everything(), cyl)无效?
因为everything()会选中所有列(包括cyl),tidyselect机制会自动去除重复的列选择,最终列顺序和原数据一致,无法实现移动效果。
效果验证
执行上述任意一种方法后,都会得到期望的结果:
# 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
内容的提问来源于stack exchange,提问作者RayVelcoro
相关产品推荐
相关产品推荐

