`mixedorder` 对 data.table 进行排序,以列名向量作为输入

问题描述 投票:0回答:1

这是我的样本数据:

library(data.table)
set.seed(47)
colsize <- 10
DT <- data.table(sortcol1 = as.numeric(sample(CJ(1:27,1:27,1:27)[,paste0(V1,V2,V3)],colsize)),
               sortcol2 = sample(CJ(c( LETTERS, " "),c(1:27),c(letters," "))[,paste0(V1,V2,V3)],colsize),
               sortcol3 = sample(CJ(c( LETTERS, " "),c(1:27),c(letters," "))[,paste0(V1,V2,V3)],colsize),
               sortcol4 = sample(CJ(c( LETTERS, " "),c(1:27),c(letters," "))[,paste0(V1,V2,V3)],colsize),
               sortcol5 = sample(CJ(c( LETTERS, " "),c(1:27),c(letters," "))[,paste0(V1,V2,V3)],colsize),
               stringsAsFactors = F)

DT
#     sortcol1 sortcol2 sortcol3 sortcol4 sortcol5
#        <num>   <char>   <char>   <char>   <char>
#  1:   241420     F12e     V10y     D23v     J10b
#  2:    71714      P1j     Q11y      D3s     F11e
#  3:    18617      E3w     U18t      25n     L14r
#  4:     4254     A12i     P15f     I27h      L9m
#  5:   131325     K27w      E8j      B6q       1q
#  6:     1958      Q1k     H23u     A18f     P23 
#  7:   151619      C1y      R7i      27q     U26l
#  8:     9262      C9n     N15o     P19q      I7t
#  9:    11518      C8l     P22a      E5g     X18z
# 10:     3224     Z26b     X17b      Y5z     Q12k

这是来自其他来源的用户输入:

input = c("sortcol2", "sortcol1");

这解决了目的,但我需要它动态合并对象

input

library(gtools)
DT[mixedorder(sortcol2, sortcol1 , decreasing = FALSE)]

DT
包含数字、字符或两者的混合。有些列可以完全是数字。

input
的长度至少为 1。可以是任何顺序。

## sample input values
input <- c("sortcol3","sortcol1")
input <- c("sortcol5")
input <- c("sortcol1","sortcol5","sortcol3") # etc

data.table::setorderv
不考虑向量中的混合字母和数值。

我需要这个在

data.table

可能的解决方案

这个功能似乎运作良好。我已经对其进行了编辑以合并

input

multi.mixedorder <-\(data, cols, na.last = TRUE, decreasing = FALSE) {
  do.call(order, c(
    lapply(cols, function(col) {
      if (is.character(data[[col]])) {
        factor(data[[col]], levels = mixedsort(unique(data[[col]])))
      } else {
        data[[col]]
      }
    }),
    list(na.last = na.last, decreasing = decreasing)
  ))
}


DT[multi.mixedorder(DT, input),]
r sorting data.table
1个回答
0
投票

可能的解决方案

这个功能似乎运作良好。我已经对其进行了编辑以合并输入。

multi.mixedorder <-\(data, cols, na.last = TRUE, decreasing = FALSE) {
  do.call(order, c(
    lapply(cols, function(col) {
      if (is.character(data[[col]])) {
        factor(data[[col]], levels = mixedsort(unique(data[[col]])))
      } else {
        data[[col]]
      }
    }),
    list(na.last = na.last, decreasing = decreasing)
  ))
}

DT[multi.mixedorder(DT, input),]
© www.soinside.com 2019 - 2024. All rights reserved.