11

I'm attempting to write a function to count the number of consecutive instances of a pattern. As an example, I'd like the string

string<-"A>A>A>B>C>C>C>A>A"

to be transformed into

"3 A > 1 B > 3 C > 2 A"

I've got a function that counts the instances of each string, see below. But it doesn't achieve the ordering effect that I'd like. Any ideas or pointers?

Thanks,

R

Existing function:

fnc_gen_PathName <- function(string) {
p <- strsplit(as.character(string), ";")
p1 <- lapply(p, table)
p2 <- lapply(p1, function(x) {
sapply(1:length(x), function(i) {
  if(x[i] == 25){
    paste0(x[i], "+ ", names(x)[i])
  } else{
    paste0(x[i], "x ", names(x)[i])
  }
})
})
p3 <- lapply(p2, function(x) paste(x, collapse = "; "))
p3 <- do.call(rbind, p3)
return(p3)
}

2 Answers2

11

As commented by @MrFlick you could try the following using rle and strsplit

with(rle(strsplit(string, ">")[[1]]), paste(lengths, values, collapse = " > "))
## [1] "3 A > 1 B > 3 C > 2 A"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
0

Here are two dplyr solutions: one regular and one with rle. Advantages are: can input multiple strings as a vector, builds a tidy intermediate dataset before (ugh) renesting.

library(dplyr)
library(tidyr)
library(stringi)

strings = "A>A>A>B>C>C>C>A>A"


data_frame(string = strings) %>%
  mutate(string_split =
           string %>%
           stri_split_fixed(">")) %>%
  unnest(string_split) %>%
  mutate(ID = 
           string_split %>%
           lag %>%
           `!=`(string_split) %>%
           plyr::mapvalues(NA, TRUE) %>%
           cumsum) %>%
  count(string, ID, string_split) %>%
  group_by(string) %>%
  summarize(new_string =
              paste(n, 
                    string_split, 
                    collapse = " > ") )

data_frame(string = strings) %>%
  group_by(string) %>%
  do(.$string %>%
       first %>%
       stri_split_fixed(">") %>%
       first %>%
       rle %>%
       unclass %>%
       as.data.frame) %>%
  summarize(new_string = 
              paste(lengths, values, collapse = " > "))
bramtayl
  • 4,004
  • 2
  • 11
  • 18