Home > Net >  Shortening a long vector in R
Shortening a long vector in R

Time:01-02

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"

CodePudding user response:

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"

CodePudding user response:

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