【问题标题】:Split string containing ordered numbers in RR中包含有序数字的拆分字符串
【发布时间】:2016-07-18 18:48:06
【问题描述】:

我有这样的字符串:

"12385402763024590"

它包含按升序和降序交替排列的数字。我想根据这些订单拆分它们。输出将是:

"1238"  "540"  "27"  "630"  "2459" "0"

我们如何在 R 中做到这一点?

【问题讨论】:

  • StackOverflow 不是代码编写服务。当 OP 提供手头的问题时,我们很感激,这是一个最小的可重现示例和迄今为止尝试过的努力/尝试。
  • 展示努力/尝试只是让我们能够更好地调整我们的答案,以解决您迄今为止遇到的具体问题(如果有的话)。我非常乐意就一般 问题提供见解,但鉴于我不知道任务的哪个部分更成问题,因此更难知道应该把重点放在哪里。你的问题的核心到底是什么?是字符串拆分吗?您必须将每个值与上一个/下一个值进行比较的部分?如何创建具有此类子集的组等。
  • @StevenBeaupré 你可能想看看我自己的答案HERE

标签: r string split


【解决方案1】:

您还可以将两个向量传递给substring

x <- "12385402763024590"
substring(x, c(1,5,8,10,13,17), c(4,7,9,12,16,17))
[1] "1238" "540"  "27"   "630"  "2459" "0" 

也许?

sp1 <- function(x){
   y <- as.numeric(strsplit(x, "")[[1]])
   n <- cumsum(rle(diff(y)<0)$lengths) +1
   substring(x, c(1, n[-length(n)]+1),   n )
}

sp1(x)
[1] "1238" "540"  "27"   "630"  "2459" "0" 

【讨论】:

    【解决方案2】:

    这是一个使用 data.table 包中的 rleid 和基础 R 中的 split 函数的选项:

    library(data.table)
    strToNum <- as.numeric(strsplit(s, "")[[1]])
    # split the string into numeric vectors
    
    sapply(split(strToNum, c(1, rleid(diff(strToNum) > 0))), paste0, collapse = "")
    # calculate the rleid for sequence in ascending or descending order and split the vector 
    # based on the run length encoding ID. Since the first element will always be classified 
    # into the first sequence, we prepend 1 in the resulting rleid.
    
    #      1      2      3      4      5      6 
    # "1238"  "540"   "27"  "630" "2459"    "0" 
    

    【讨论】:

      【解决方案3】:

      这是我自己使用基础 R 的解决方案:

      f <- function(r, char_s){
          cuts <- c(0, which(diff(r) != 1), length(r))
          sapply(seq_along(tail(cuts,-1)), function(x) 
                        paste0(char_s[r[(cuts[x]+1):cuts[x+1]]],collapse=""))
      }
      
      char_s <- strsplit(s, "")[[1]]
      dif <- c(1,diff(as.numeric(char_s)))
      
      # ascending orders
      f(which(dif>0), char_s)
      # [1] "1238" "27"   "2459"
      
      # descending orders
      f(which(dif<0), char_s)
      # [1] "540" "630" "0" 
      

      【讨论】:

      • 我之前已经给你加了一个。
      • 或者另一个选项是sub,即scan(text=sub("(.{4})(.{3})(.{2})(.{3})(.{4})(.)", "\\1,\\2,\\3,\\4,\\5", str1), what = numeric(), sep=",")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多