I would have a column where the data looks like this:
M999-00001
M999-00002
...
Is there a way to remove all the 'M's in the column in R?
You can use sub in base R to remove "m" from the beginning of the column names.
Use gsub() function to remove a character from a string or text in R.
To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.
To remove all columns with a common suffix from an R data frame, you need to use the grep() function. This function identifies and returns a vector with all columns that share the suffix. You can use this vector as an argument of the select() function to remove the columns from the data frame.
We can use sub
df1[,1] <- sub("^.", "", df1[,1])
Or use substring
substring(df1[,1],2)
df1 <- data.frame(Col1 = c("M999-00001", "M999-0000"), stringsAsFactors=FALSE)
You can use gsub function for the same
Col1 <- gsub("[A-z]","",Col1)
[1] "999-00001" "999-0000"
Col1 = c("M999-00001", "M999-0000")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With