salhin
salhin

Reputation: 2654

Remove part of string using gsub

I used the below code to remove the part "(MV)" from the end of every string in a vector (specifically row number 1 for all columns and skip column 1 as shown in the code), however, it removed every M, V and MV in the vector even if it is at the start of the string.

df[1,(-1)]<-gsub("[(MV)]","",df[1,(-1)])

How to only remove the (MV) part at the end of each string without affecting the rest of the rest?

Here is a reproducible example:

structure(list(X1 = structure(c(NA, 5447), class = "Date"), X2 = c("AVON(MV)", 
"28.34"), X3 = c("BA.(MV)", "750.07"), X4 = c("CMRG(MV)", "10.040000000000001"
), X5 = c("COB(MV)", "143.22999999999999")), .Names = c("X1", 
"X2", "X3", "X4", "X5"), row.names = c(NA, -2L), class = "data.frame")

Upvotes: 0

Views: 2181

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

Are you sure that the first row is not supposed to be the column headers? That's not really the way data is normally set up and will cause issues if you need to use the numbers for calculations.

Anyway, to remove the (MV) from each string, try the fixed argument in gsub, and make the pattern "(MV)"

df[1,-1] <- gsub("(MV)", "", df[1,-1], fixed=TRUE)
df
#           X1    X2     X3                 X4                 X5
# 1       <NA>  AVON    BA.               CMRG                COB
# 2 1984-11-30 28.34 750.07 10.040000000000001 143.22999999999999

But I think you need to take a look at this data more closely because it doesn't seem to be set up correctly.

Upvotes: 1

Related Questions