R: find largest common substring starting at the beginning

后端 未结 11 2703
星月不相逢
星月不相逢 2021-02-19 18:33

I\'ve got 2 vectors:

word1 <- \"bestelling\"   
word2 <- \"bestelbon\"

Now I want to find the largest common substring that starts at the

11条回答
  •  再見小時候
    2021-02-19 18:57

    fun <- function(words) {
      #extract substrings from length 1 to length of shortest word
      subs <- sapply(seq_len(min(nchar(words))), 
                     function(x, words) substring(words, 1, x), 
                     words=words)
      #max length for which substrings are equal
      neqal <- max(cumsum(apply(subs, 2, function(x) length(unique(x)) == 1L)))
      #return substring
      substring(words[1], 1, neqal)
    }
    
    words1 <- c("bestelling", "bestelbon")
    fun(words1)
    #[1] "bestel"
    
    words2 <- c("bestelling", "stel")
    fun(words2)
    #[1] ""
    

提交回复
热议问题