在 R 中的矢量或数据框中按单位名称按大小对对象进行排序

Sorting objects by size with unit denominations in a vector or data frame in R

我正在尝试按降序对对象大小的向量进行排序并创建一个数据框。我遇到了排序问题,因为数字有单位名称(例如 Kb、Mb 等),我想知道如何按升序或降序对数字进行排序?因为数字有面额,所以它们本质上被视为字符向量,因此不能按大小排序。

示例 1:

library(dplyr)

l <- list(1:1e6, 1:1e1, 1:1e3, 1:1e7)
l <- sapply(
    l,
    function(x){
        object.size(x) %>% format(units = "auto")
    }
)

# Alt. A: Sorting the vector before coercing to dataframe
sort(l) %>% as.data.frame() 

A data.frame: 4 × 1
.
<chr>
96 bytes
4 Kb
38.1 Mb
3.8 Mb

# Alt. B: Coerce to dataframe then sort using arrange()
as.data.frame(l) %>% arrange(desc(names(.)[1]))

A data.frame: 4 × 1
l
<chr>
3.8 Mb
96 bytes
4 Kb
38.1 Mb

期望的输出:

A data.frame: 4 × 1
l
<chr>
38.1 Mb
3.8 Mb
4 Kb
96 bytes

问题是您的 sapply 循环只保留格式化输出,这更难排序。使用 purrr 您可以在数据框中为每次迭代存储两个值并将结果绑定在一起。所以你可以这样做:

library(dplyr)

l <- list(1:1e6, 1:1e1, 1:1e3, 1:1e7)
l_1 <- purrr::map_df(l, function(x) {
  tibble(
    size_raw = object.size(x),
    size = size_raw %>% format(units = "auto")
  )
})

l_1 %>% 
  arrange(-size_raw)
#> # A tibble: 4 × 2
#>   size_raw       size    
#>   <objct_sz>     <chr>   
#> 1 40000048 bytes 38.1 Mb 
#> 2 4000048 bytes  3.8 Mb  
#> 3 4048 bytes     4 Kb    
#> 4 96 bytes       96 bytes

reprex package (v2.0.1)

于 2022 年 3 月 16 日创建