How to extract the remaining substring of a string

Viewed 68

In the column "a", I have the full words and in the word "b", I have a substring of the word. How I can find the remaining substring. The ideal result should look like "column_to_extract" column.

a <- c("clean", "player", "rubbish", "lock")
b<- c("ean", "er", "bbish", "ck")

df1 <- data.frame(a,b)


The result should be:

        a     b column_to_extract
1   clean   ean                cl
2  player    er              play
3 rubbish bbish                ru
4    lock    ck                lo

3 Answers
library(tidyverse)
df1 %>% mutate(column_to_extract = str_replace(a, b, ""))
        a     b column_to_extract
1   clean   ean                cl
2  player    er              play
3 rubbish bbish                ru
4    lock    ck                lo

A Base R option would be:

# Split into list of strsplit row vectors
list <- apply(df1, 1, strsplit, split = "")

# Find those that do not match and return 
cbind(df1, "column_to_extract" = sapply(list, function(x){
  paste(x[[1]][!(x[[1]] %in% x[[2]])], collapse = "")
}))

# Yields
#        a     b column_to_extract
#1   clean   ean                cl
#2  player    er              play
#3 rubbish bbish                ru
#4    lock    ck                lo

You can use str_remove from stringr which is vectorized. It is similar to using str_replace with replacement as empty string. ("").

library(dplyr)
library(stringr)

df1 %>%
  mutate(column_to_extract = str_remove(a, b), 
         column_to_extract2 = str_replace(a, b, ""))

#        a     b column_to_extract column_to_extract2
#1   clean   ean                cl                 cl
#2  player    er              play               play
#3 rubbish bbish                ru                 ru
#4    lock    ck                lo                 lo
Related