How to remove hash sign at last position from every value in R data frame column?



To remove hash at last position from every value in R data frame column, we can follow the below steps −

  • First of all, create a data frame with a column having hash at last position in every value.

  • Then, use gsub function to remove hash at last position from every value in the column.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(c("5#","7#","2#","3#","10#","4#","1#"),25,replace=TRUE) df<-data.frame(x) df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x 1 7# 2 2# 3 5# 4 7# 5 10# 6 5# 7 2# 8 5# 9 4# 10 1# 11  4# 12 10# 13  1# 14  5# 15  2# 16  2# 17  7# 18  3# 19  7# 20 10# 21  7# 22  5# 23 10# 24 10# 25 10#

Remove hash sign from last position

Using gsub function to remove hash at last position from every value in column x of data frame df as shown below −

x<-sample(c("5#","7#","2#","3#","10#","4#","1#"),25,replace=TRUE) df<-data.frame(x) df$new_x<-gsub("#$","",df$x) df

Output

 x new_x 1 7# 7 2 2# 2 3 5# 5 4 7# 7 5 10# 10 6 5# 5 7 2# 2 8 5# 5 9 4# 4 10 1# 1 11 4# 4 12 10# 10 13 1# 1 14 5# 5 15 2# 2 16 2# 2 17 7# 7 18 3# 3 19 7# 7 20 10# 10 21 7# 7 22 5# 5 23 10# 10 24 10# 10 25 10# 10
Updated on: 2021-11-16T05:36:56+05:30

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements