0

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")
3
  • 3
    You can use the fixed argument in gsub, probably with "(MV)" as your pattern. Example: x <- "MV(MV)"; gsub("(MV)", "", x, fixed=TRUE) Please provide a reproducible example so we know exactly what you're doing. Commented Oct 30, 2014 at 19:05
  • @RichardScriven I updated the question with a reproducible example Commented Oct 30, 2014 at 20:00
  • 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. Commented Oct 30, 2014 at 20:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is supposed to be column headers but it comes as it is from the excel file. I thought it would be easier to clean it up as row than as column names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.