I have this data in R:
string_1 = c("newyork 123", "california 123", "washington 123")
string_2 = c("123 red", "123 blue", "123 green")
my_data = data.frame(string_1, string_2)
I want to "subtract" string_2
from string_1
. The result would look something like this:
"newyork", "california", "washington"
I tried to do this:
library(tidyverse)
# did not work as planned
> str_remove(string_1, "string_2")
[1] "newyork 123" "california 123" "washington 123"
But this is not performing a "full" subtraction.
Thank you!
You could split both strings and find the set difference of them.
mapply(setdiff, strsplit(string_1, "\\s+"), strsplit(string_2, "\\s+"))
# [1] "newyork" "california" "washington"
library(purrr)
list1 <- str_split(string_1, pattern = " ")
list2 <- str_split(string_2, pattern = " ")
a <- map2(list1, list2, function(x, y){
output <- setdiff(x, y)
return(output)
}) %>% unlist()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With