arielle
arielle

Reputation: 945

Pasting a string on every other element of a vector

I have a vector like this:

test <- c("a","b","c","d")
test
[1] "a" "b" "c" "d"

And I would like to paste a string, e.g. "_2", onto every other element of the vector, to get this:

"a" "b_2" "c" "d_2"

I tried this command:

ifelse(test %in% seq(1, length(test), 2), test, paste(test, "_2", sep=""))

but this just gives me:

"a_2" "b_2" "c_2" "d_2"

which is wrong. Any suggestions on how to properly do this? Thank you!

Upvotes: 2

Views: 1448

Answers (3)

Sotos
Sotos

Reputation: 51592

Another option would be,

test[c(FALSE, TRUE)] <- paste0(test[c(FALSE, TRUE)], '_2')
test
#[1] "a"   "b_2" "c"   "d_2"

Upvotes: 2

Daniel Anderson
Daniel Anderson

Reputation: 2424

How about

paste0(c("a","b","c","d"), c("", "_2"))

[1] "a"   "b_2" "c"   "d_2"

Upvotes: 6

Rentrop
Rentrop

Reputation: 21497

x <- c("a","b","c","d")
x[seq(2, length(x), by=2)] <- paste0(x[seq(2, length(x), by=2)], "_2")
x

this gives:

"a"   "b_2" "c"   "d_2"

Upvotes: 1

Related Questions