Stefano Stefano - 3 months ago 22
R Question

R - Concatenate string elements based on another array

I have a simple issue and I found a very complicated (C stylish) solution and I am wondering if there is something much simpler than this.
I have two arrays:

y <- c("A","B","C","D","E")
d <- c(1,3,1)


and I need to get an array as

"A","B-C-D","E"


so based on the distribution
d
, aggregate the elements of
y
separated by a
-
(or any other separator).

I did this

old_y <- y
y <- NULL

k <- 1
for (i in 1:length(d)) {
y[i] <- as.character(old_y[k])
j <- 1
while(d[i]>j) {
y[i] <- paste0(y[i], "-", as.character(old_y[k+j]))
j <- j + 1
}
k <- k + d[i]
}

Answer

We can use tapply on 'y' grouped by the sequence of 'd' replicated by 'd' and paste the elements of 'y' together.

unname(tapply(y, rep(seq_along(d), d), FUN = paste, collapse="-"))
#[1] "A"     "B-C-D" "E"