【问题标题】:Why does stringr::str_order(x, numeric = T) sort data differently in conjunction with dplyr::arrange than with hard brackets?为什么 stringr::str_order(x, numeric = T) 与 dplyr::arrange 结合使用的数据排序方式与使用硬括号不同?
【发布时间】:2022-01-14 17:43:39
【问题描述】:

我正在尝试通过包含一些数值的文本列来排列 data.frame:

foo <- data.frame(x = c("A100", "A1", "A2", "A10", "A11"))

我正在尝试使用 stringr::str_order(foo$x, numeric = TRUE) 或类似的东西对其进行数字排序。我正在尝试将其与 dplyr::arrange 一起使用,但排列不正确。这是我所做的:

dplyr::arrange(foo, stringr::str_order(x,numeric = T))

在我的机器上,这将按 A11、A100、A1、A2、A10 的顺序返回值,而不是 A1、A2、A10、A11、A100。此代码正常工作:

foo[stringr::str_order(foo$x,numeric = T),]

我希望它们能做同样的事情,但至少在我的机器(Windows 10,R 版本 4.1.0)和我兄弟的机器(Mac,R 版本 4.0.2)上没有。

我的问题是,为什么输出不同?我错过了什么?有没有办法让 str_order 和安排一起工作?

我希望能够使用 dplyr::arrange 对该列进行排序,这样我就不需要跟踪我使用过的所有位置。

感谢您的想法和时间!

【问题讨论】:

  • 如果答案之一解决了您的问题,请考虑接受。

标签: r text dplyr stringr


【解决方案1】:

请注意,str_order 就像 order 一样以升序方式返回每个元素包含的索引,例如:

str_order(foo$x,numeric = T)
[1] 2 3 4 5 1

表示最后一个元素,即当前最大的元素在位置1,而第一个元素,即最小的,在当前向量的位置2。

另一方面,arrange 占据了元素应该被排序一次的位置,即排名(没有关系)。

y <- c(100,1,2,10,11)
order(y)
[1] 2 3 4 5 1 # We do not want this
rank(y)
[1] 5 1 2 3 4 # We want this.

请注意,排名表明最小的对象 (1) 位于位置 2,而最大的对象 (5) 位于位置 1

现在要获得这个,只需订购有序向量。因此:

arrange(foo, order(str_order(x,numeric = T)))
     x
1   A1
2   A2
3  A10
4  A11
5 A100

【讨论】:

    【解决方案2】:

    你可以使用:

    dplyr::arrange(foo, match(x, stringr::str_sort(x,numeric = T)))
    
         x
    1   A1
    2   A2
    3  A10
    4  A11
    5 A100
    

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多