Eddie Eddie - 3 months ago 10
R Question

Find and replace with a certain condition

I have some strings which the "spaces" are removed mistakenly. But I was lucky that I had the original strings as well, I wish to replace the changed strings with the original strings. Let's my data is:

#dts1

Id changed Original

1 cfd a b c
2 abc cf d


All the spaces of original data are removed. I wish my program go to the changed column and for instance find cfd and understand that it was cf d and replace it.

So, my ideal output is

#output

Id changed

1 cf d
2 a b c


Any tip is really appreciated.

dts1 <- structure(list(original = c("a b c", "cf d"), changed = c("cfd",
"abc")), .Names = c("original", "changed"), row.names = c(NA,
-2L), class = "data.frame")

Answer

Just strip the white space out of dts1$original and match it up?

dts1$original[match(dts1$changed, gsub("\\s+","",dts1$original))]
#[1] "cf d"  "a b c"

Where:

dts1 <- structure(list(original = c("a b c", "cf d"), changed = c("cfd", 
"abc")), .Names = c("original", "changed"), row.names = c(NA, 
-2L), class = "data.frame")
Comments