alki
alki

Reputation: 3574

R: Insert vector into every other character of string

Suppose you have a string and a vector of the same length:

require(stringi)

string <- "ABCDEFGHIJKLMN"
vector <- 1:stri_length(string)

What would be a quick way to output this?

# A1B2C3D4E5F6G7H8I9J10K11L12M13N14

Or output a vector that looks like this (if simpler):

vector2
# "A" "1" "B" "2" "C" "3" "D" "4" ........

Upvotes: 3

Views: 562

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

There's probably a better way but here's my attempt

paste(c(rbind(strsplit(string, "")[[1]], vector)), collapse = "")
## [1] "A1B2C3D4E5F6G7H8I9J10K11L12M13N14"

If you want the second output, just remove the paste part as in

c(rbind(strsplit(string, "")[[1]], vector))
#  [1] "A"  "1"  "B"  "2"  "C"  "3"  "D"  "4"  "E"  "5"  "F"  "6"  "G"  "7"  "H"  "8"  "I"  "9"  "J"  "10"
# [21] "K"  "11" "L"  "12" "M"  "13" "N"  "14"

Upvotes: 2

Related Questions