Stefano - 10 months ago 66

R Question

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`

`y`

`-`

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"
```

Source (Stackoverflow)