简体   繁体   中英

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]
}

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM