【问题标题】:Shortening a long vector in R缩短R中的长向量
【发布时间】:2022-01-01 18:14:38
【问题描述】:

向量 ab 可以在 Base R 中使用 toString(width = 10) 缩短,从而得到一个以 .... 结尾的较短向量

但是,我想知道如何使缩短的向量以..., last vector element 结尾?

我的desired_output 如下所示。

a <- 1:26
b <- LETTERS  

toString(a, width = 10)
# [1] "1,2,...."
desired_output1 = "1,2,...,26"

toString(b, width = 10)
# [1] "A,B,...."
desired_output2 = "A,B,...,Z"

【问题讨论】:

  • 为了清楚起见,用例是什么?

标签: r string vector


【解决方案1】:

你可以只添加结尾。

paste(toString(a, width = 10), a[length(a)], sep=", ")  
[1] "1, 2, ...., 26"
paste(toString(b, width = 10), b[length(b)], sep=", ")  
[1] "A, B, ...., Z"

【讨论】:

    【解决方案2】:

    在应用toString之后,我们可以使用sub来删除format的子串

    f1 <- function(vec, n = 2) { 
       
        gsub("\\s+", "", 
         sub(sprintf("^(([^,]+, ){%s}).*, ([^,]+)$", n), "\\1...,\\3", toString(vec)))
    
    }
    

    -测试

    > f1(a)
    [1] "1,2,...,26"
    > f1(b)
    [1] "A,B,...,Z"
    > f1(a, 3)
    [1] "1,2,3,...,26"
    > f1(b, 3)
    [1] "A,B,C,...,Z"
    > f1(a, 4)
    [1] "1,2,3,4,...,26"
    > f1(b, 4)
    [1] "A,B,C,D,...,Z"
    

    【讨论】:

    【解决方案3】:

    我们可以这样做: 创建一个函数,提取向量的前两个元素和最后一个元素并将它们粘贴在一起:

    my_func <- function(x) {
      a <- paste(x[1:2], collapse=",")
      b <- tail(x, n=1)
      paste0(a,",...,",b)
    }
    
    my_func(a)
    [1] "1,2,...,26"
    
    my_func(b)
    [1] "A,B,...,Z"
    

    【讨论】:

      【解决方案4】:
      library(stringr)
      
      a <- 1:26
      b <- LETTERS  
      
      
      reduce_string <- function(x, n_show) {
          
          str_c(x[1:n_show], collapse = ',') %>% 
              str_c('....,', x[[length(x)]])
          
      }
      
      reduce_string(a, 2)
      #> [1] "1,2....,26"
      

      reprex package (v2.0.1) 于 2022-01-02 创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-22
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多