Zach
Zach

Reputation: 37

R str_replace_all Does Not Seem to Be Working Correctly

The following line of code does not appear to be working correctly for me:

df$Combined2<-str_replace_all(df$Combined,"0[+]","")

The string cell that I am questioning and trying to break apart follows:

 0+0+0+0+0+0+0+0+0+0+0+0+0+Ultimate+0+0+0+0+0+0+0+Multiple 8x10+0+0+0+3x5+0+0+0+0+0+0

What I would like for the end results would be something like the following:

Ultimate+Multiple 8x10+3x5

But it looks like the following:

Ultimate+Multiple 8x13x5+0

I cannot figure out what I am doing incorrectly here. It looks like it sort of combined the 8x10 & 3x5 fields, but they truly are supposed to be different and not combined.

Actually - I might have just figured this out because I am removing the 0+s (or 0[+] and that it why it is sort of combining the fields. Even though I solved it I still think it is worthy of sharing with the group - I hope you agree.

Upvotes: 0

Views: 256

Answers (1)

Onyambu
Onyambu

Reputation: 79208

You can use gsub:

gsub('(?<!\\d)0\\+?|[+]0', '', vec, perl = T)

[1] "Ultimate+Multiple 8x10+3x5"

data

vec = '0+0+0+0+0+0+0+0+0+0+0+0+0+Ultimate+0+0+0+0+0+0+0+Multiple 8x10+0+0+0+3x5+0+0+0+0+0+0'

Upvotes: 2

Related Questions