2

I'm looking to rename certain values of my column based upon a certain string. My current data resembles this example:

PlayerID

Hank_Aaron+7
Babe Ruth+5
MMM + 7
Willie Mayes+1
MMM + 3

I would like to rename all observations that start with "MMM" to be just "MMM". For example, I want the above table to ultimately look like this:

PlayerID

Hank_Aaron+7
Babe Ruth+5
MMM
Willie Mayes+1
MMM

I also need to keep the column in the same dataframe so that I can use it for regressions. Thank you in advance!

2 Answers 2

2

With grep, find the position index of 'MMM' string, extract those, then do an assignment (assuming 'PlayerID' is character class and not factor class)

df1$PlayerID[grep("^MMM", df1$PlayerID)] <- "MMM"
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that seems to have done it. Thank you so much!
0

We can use startsWith :

df$PlayerID[startsWith(df$PlayerID, 'MMM')] <- 'MMM'

We can also use this in replace :

df$PlayerID <- replace(df$PlayerID, startsWith(df$PlayerID, 'MMM'), 'MMM')
df
#        PlayerID
#1   Hank_Aaron+7
#2    Babe Ruth+5
#3            MMM
#4 Willie Mayes+1
#5            MMM

data

df <- structure(list(PlayerID = c("Hank_Aaron+7", "Babe Ruth+5", "MMM + 7", 
"Willie Mayes+1", "MMM + 3")), class = "data.frame", row.names = c(NA, -5L))

2 Comments

Thank you for your response Ronak! Is it possible to do this in the opposite direction? For example, what if I wanted to re-name the Player-ID column according to the number at the very end of PlayerID? As such: ``` PlayerID NewID Hank Aaron + 7 7 Babe Ruth + 5 5 Ted Williams + 2 2 Hank Aaron + 5 5 ``` Is there maybe an endswith command? Also if you believe this question merits a new post please let me know.
There is endsWith as well but it needs a fix suffix like "5", or "6" etc, writing this for all combinations can be tiring. So you can use grepl here to match with any digit df$PlayerID[grepl('\\d$', df$PlayerID)] <- 'MMM'

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.