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:
[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.