Reputation: 191
a <- c("abc","efg","hij","klm","nop","qrs")
I want to collapse string based on alternate delimiter(,). ie.
"abcefg" "hijklm" "nopqrs"
Upvotes: 2
Views: 226
Reputation: 887008
We can use c(TRUE, FALSE)
to extract the alternating elements of 'a' and paste
with the elements extracted based on c(FALSE, TRUE)
. By using c(TRUE, FALSE)/c(FALSE, TRUE)
, this will extract the elements based on the recycling.
paste0(a[c(TRUE, FALSE)], a[c(FALSE, TRUE)])
#[1] "abcefg" "hijklm" "nopqrs"
Or
sprintf('%s%s', a[c(TRUE, FALSE)], a[c(FALSE, TRUE)])
#[1] "abcefg" "hijklm" "nopqrs"
A slightly more efficient process would be
indx1 <- seq(1, length(a), 2)
indx2 <- seq(2, length(a), 2)
sprintf('%s%s', a[indx1], a[indx2])
#[1] "abcefg" "hijklm" "nopqrs"
Upvotes: 3