Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shortening a long vector in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading