String concatenation using an apply function in R

Viewed 2253

I have the following code whose purpose is to transcribe a sequence in to tuples of three. It executes correctly, but is particularly slow when applied to very large data sets (i.e. millions of rows).

I suspect the culprit is the "for - loops" across a vector (particularly the for y: loop), and feel there should be a more efficient method using one of the apply functions - unfortunately I'm not overly familiar with this approach and would like to request some assistance (please!).

M.Order <- function(in.vector) {
  return.str <- vector()
  in.vector <- strsplit(in.vector, ' > ', fixed = T)
  for (x in 1:length(in.vector)) {
      output <- NULL
      if(length(in.vector[[x]]) == 1) {
          output <- paste0(in.vector[[x]], '|NULL|NULL')
      } else if(length(in.vector[[x]]) == 2) {
          output <- paste(c(in.vector[[x]][1], in.vector[[x]][2],'NULL'), collapse='|')
      } else if(length(in.vector[[x]]) == 3) {
          output <- paste(in.vector[[x]], collapse = '|')
      } else for (y in 1:(length(in.vector[[x]])-2)) {
          output <- ifelse(length(output) == 0
                          ,paste(in.vector[[x]][y:(y+2)], collapse = '|')
                          ,paste0(output, ' > ', paste(in.vector[[x]][y:(y+2)], collapse = '|'))
                          )
      }
      return.str[x] <- output
  }
return (return.str)
}

orig.str <- rbind.data.frame(
  'A > B > C > B > B > A > B > A > C',
  'A > B',
  'A > C > B',
  'A',
  'A > B > D > C')

colnames(orig.str) <- 'Original'
orig.str$Processed <- M.Order(as.character(orig.str$Original))
orig.str

which returns (correctly)

                           Original                                             Processed
1 A > B > C > B > B > A > B > A > C A|B|C > B|C|B > C|B|B > B|B|A > B|A|B > A|B|A > B|A|C
2                             A > B                                              A|B|NULL
3                         A > C > B                                                 A|C|B
4                                 A                                           A|NULL|NULL
5                     A > B > D > C                                         A|B|D > B|D|C
3 Answers
Related