Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove prefix from all data in a single column in R

Tags:

r

prefix

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?

like image 403
Miyii Avatar asked Aug 12 '16 03:08

Miyii


People also ask

How do I remove a prefix from a column name in R?

You can use sub in base R to remove "m" from the beginning of the column names.

How do I remove text from a column in R?

Use gsub() function to remove a character from a string or text in R.

How do I remove a value from a column 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.

How do I remove a suffix from a variable in R?

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.


2 Answers

We can use sub

df1[,1] <- sub("^.", "", df1[,1])

Or use substring

substring(df1[,1],2)

data

df1 <- data.frame(Col1 = c("M999-00001", "M999-0000"), stringsAsFactors=FALSE)
like image 135
akrun Avatar answered Nov 14 '22 22:11

akrun


You can use gsub function for the same

Col1 <- gsub("[A-z]","",Col1)
[1] "999-00001" "999-0000" 

data

Col1 = c("M999-00001", "M999-0000")
like image 39
Arun kumar mahesh Avatar answered Nov 14 '22 23:11

Arun kumar mahesh