gpt4 book ai didi

r - 如何按列顺序对 tibble 进行排序? (第一列,第二列,第三列......)

转载 作者:行者123 更新时间:2023-12-01 23:16:44 25 4
gpt4 key购买 nike

我有一个小标题,其中包含任意数量的列。这些列是按顺序插入的,因此它们的索引(第一、第二……)是有意义的。

我正在尝试按第一列、第二列、第三列等对小标题进行排序。

我宁愿继续使用 dplyr::arrange() 来与我的框架保持一致,但如果无法做到,我很乐意接受任何解决方案。

此外,如果可以最后考虑缺失值,那将是一个很好的优势。

这是一个可重现的示例,其中包含我的预期输出和一些失败的尝试:

library(tidyverse)
set.seed(0)
x=as_tibble(mtcars)[1:4] %>% sample_n(5)
x
#> # A tibble: 5 x 4
#> mpg cyl disp hp
#> <dbl> <dbl> <dbl> <dbl>
#> 1 15.2 8 276. 180
#> 2 19.2 8 400 175
#> 3 21.4 6 258 110
#> 4 14.3 8 360 245
#> 5 21 6 160 110

# **** EXPECTED OUTPUTS: ****

arrange(x, mpg, cyl, disp, hp)
#> # A tibble: 5 x 4
#> mpg cyl disp hp
#> <dbl> <dbl> <dbl> <dbl>
#> 1 14.3 8 360 245
#> 2 15.2 8 276. 180
#> 3 19.2 8 400 175
#> 4 21 6 160 110
#> 5 21.4 6 258 110
arrange(x, hp, disp, cyl, mpg)
#> # A tibble: 5 x 4
#> mpg cyl disp hp
#> <dbl> <dbl> <dbl> <dbl>
#> 1 21 6 160 110
#> 2 21.4 6 258 110
#> 3 19.2 8 400 175
#> 4 15.2 8 276. 180
#> 5 14.3 8 360 245

# **** MY FAILED ATTEMPTS: ****

arrange(x, all_of(colnames(x)))
#> Error: arrange() failed at implicit mutate() step.
#> * Problem with `mutate()` column `..1`.
#> i `..1 = all_of(colnames(x))`.
#> i `..1` must be size 5 or 1, not 4.
arrange(x, !!all_of(colnames(x)))
#> Error: arrange() failed at implicit mutate() step.
#> * Problem with `mutate()` column `..1`.
#> i `..1 = <chr>`.
#> i `..1` must be size 5 or 1, not 4.
arrange(x, !!!all_of(names(x)))
#> # A tibble: 5 x 4
#> mpg cyl disp hp
#> <dbl> <dbl> <dbl> <dbl>
#> 1 15.2 8 276. 180
#> 2 19.2 8 400 175
#> 3 21.4 6 258 110
#> 4 14.3 8 360 245
#> 5 21 6 160 110
do.call(arrange, x, colnames(x))
#> Warning in if (quote) args <- lapply(args, enquote): the condition has length >
#> 1 and only the first element will be used
#> Error in if (quote) args <- lapply(args, enquote): argument is not interpretable as logical
do.call(arrange, x, list(colnames(x)))
#> Error in if (quote) args <- lapply(args, enquote): argument is not interpretable as logical

reprex package 创建于 2021-08-10 (v2.0.0)

最佳答案

由于 arrange_all 已被弃用,您可以在 arrange 中使用 across

library(dplyr)
x %>% arrange(across())

# A tibble: 5 x 4
# mpg cyl disp hp
# <dbl> <dbl> <dbl> <dbl>
#1 14.3 8 360 245
#2 15.2 8 276. 180
#3 19.2 8 400 175
#4 21 6 160 110
#5 21.4 6 258 110

对于反向你可以做-

x %>% arrange(across(.cols = ncol(.):1))

# A tibble: 5 x 4
# mpg cyl disp hp
# <dbl> <dbl> <dbl> <dbl>
#1 21 6 160 110
#2 21.4 6 258 110
#3 19.2 8 400 175
#4 15.2 8 276. 180
#5 14.3 8 360 245

在基础 R 中,您可以使用 do.callorder -

#1.
x[do.call(order, x), ]

#2.
x[do.call(order, rev(x)), ]

关于r - 如何按列顺序对 tibble 进行排序? (第一列,第二列,第三列......),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68722592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com