sam.mulholland
sam.mulholland

Reputation: 15

Is there an R function to remove suffix from data sets

I am trying to remove a suffix from a dataset.

I would normally use the function

sub("/1","",x)

however within the dataset there are examples earlier in the string which have the same formatting. Example below:

zz <- data.frame(a = c(1,2,3,4),
                     b = c("JTI18A/123456","JTI19A/123456","JTI19A/123456/1","JTI18A/123456"))

I only want the suffix "/1" removed from the third string. Using the sub function above, this would remove "/1" from all data sets rather than only the suffix.

Upvotes: 1

Views: 308

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389047

In regex, suffix can be specified with $ which is end of the string.

zz$b <- sub("/1$","",zz$b)
zz$b

#[1] "JTI18A/123456" "JTI19A/123456" "JTI19A/123456" "JTI18A/123456"

Upvotes: 1

Related Questions