Reputation: 958
I want to remove a part of a string (based on another column) and I am interested in the remainder of the string...
Example:
dt <- data.frame(SomeText = c("ABCDEF", "ABCDEF", "ABCDEF"),
ToRemove = c("A", "CDE", ""),
WantedResult = c("BCDEF", "ABF", "ABCDEF"))
> dt
SomeText ToRemove WantedResult
1 ABCDEF A BCDEF
2 ABCDEF CDE ABF
3 ABCDEF ABCDEF
Thus (line 2 as example), remove 'CDE' from 'ABCDEF' so we are left with 'ABF'
Upvotes: 2
Views: 797
Reputation: 388817
Replace empty patterns with ^$
dt$ToRemove[dt$ToRemove == ''] <- '^$'
and then use stringr::str_remove
which is vectorised.
dt$result <- stringr::str_remove(dt$SomeText, dt$ToRemove)
dt
# SomeText ToRemove result
#1 ABCDEF A BCDEF
#2 ABCDEF CDE ABF
#3 ABCDEF ^$ ABCDEF
Upvotes: 5