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

Copy and insert modified strings into a vector without sorting

Let’s say I have a vector of strings:

vec <- c("D", "A", "B", "A")

I would like to insert a modified string (concatenate "_2" at the end of the strings) immediately after the original string, without sorting.

Expected output:

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

[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

I am looking for solutions simpler than the one I shared below, which I think could be unnecessarily over-complicated.

>Solution :

Try c + rbind along with paste0

> c(rbind(vec, paste0(vec, "_2")))
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

or a longer version with outer

> c(t(outer(vec, c("", "_2"), paste0)))
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

If you don’t mind the efficiency, you can try

> scan(text = gsub("(.*)", "\\1 \\1_2", vec), what = "", quiet = TRUE)
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

since scan might be slow when having long vectors.

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