Shortening a long vector in R

Viewed 84

Vectors a and b can be shortened using toString(width = 10) in Base R resulting in a shorter vector that ends in ....

However, I wonder how I can make the shortened vector to end in ..., last vector element?

My desired_output is shown below.

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"

4 Answers

You could just add the end on.

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"

After applting the toString, we may use sub to remove the substring to format

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

}

-testing

> 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"

We could do it this way: Creating a function that extraxt the first two elements and the last element of the vector and paste them together:

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"
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"

Created on 2022-01-02 by the reprex package (v2.0.1)

Related