title: How to remove common parts of strings in a character vector in R?
body: <p>Assume a character vector like the following</p>
  
  <pre><code>file1_p1_analysed_samples.txt
  file1_p1_raw_samples.txt
  f2_file2_p1_analysed_samples.txt
  f3_file3_p1_raw_samples.txt
  </code></pre>
  
  <p>Desired output:</p>
  
  <pre><code>file1_p1_analysed
  file1_p1_raw
  file2_p1_analysed
  file3_p1_raw
  </code></pre>
  
  <p>I would like to compare the elements and remove parts of the string from start and end as much as possible but keep them unique.   </p>
  
  <p>The above one is just an example. The parts to be removed are not common to all elements. I need a general solution independent of the strings in the above example. </p>
  
  <p>So far I have been able to chuck off parts that are common to all elements, provided the separator and the resulting split parts are of same length. Here is the function,</p>
  
  <pre><code>mf &lt;- function(x,sep){
      xsplit = strsplit(x,split = sep)
      xdfm &lt;- as.data.frame(do.call(rbind,xsplit))
      res &lt;- list()
      for (i in 1:ncol(xdfm)){
          if (!all(xdfm[,i] == xdfm[1,i])){
              res[[length(res)+1]] &lt;- as.character(xdfm[,i])
          }
      }
      res &lt;- as.data.frame(do.call(rbind,res))
      res &lt;- apply(res,2,function(x) paste(x,collapse="_"))
      return(res)
  }
  </code></pre>
  
  <p>Applying the above function:</p>
  
  <pre><code> a = c("a_samples.txt","b_samples.txt")
   mf(a,"_")
    V1  V2
   "a" "b"
  </code></pre>
  
  <p>2.</p>
  
  <pre><code>&gt; b = c("apple.fruit.txt","orange.fruit.txt")
  &gt; mf(b,sep = "\\.")
        V1       V2
   "apple" "orange"
  </code></pre>
  
  <p>If the resulting split parts are not same length, this doesn't work. </p>