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


To remove hyphen 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 hyphen at last position in every value.

  • Then, use gsub function to remove hyphen 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("43-","12-","45-","30-","14-","25-","31-","37-"),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  37-
2  14-
3  37-
4  30-
5  31-
6  30-
7  37-
8  12-
9  37-
10 43-
11 30-
12 37-
13 25-
14 37-
15 45-
16 14-
17 45-
18 12-
19 43-
20 30-
21 12-
22 31-
23 12-
24 25-
25 31-

Remove hyphen sign from last position

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

x<-sample(c("43-","12-","45-","30-","14-","25-","31-","37-"),25,replace=TRUE)
df<-data.frame(x)
df$new_x<-gsub("-$","",df$x)
df

Output

   x  new_x
1  37- 37
2  14- 14
3  37- 37
4  30- 30
5  31- 31
6  30- 30
7  37- 37
8  12- 12
9  37- 37
10 43- 43
11 30- 30
12 37- 37
13 25- 25
14 37- 37
15 45- 45
16 14- 14
17 45- 45
18 12- 12
19 43- 43
20 30- 30
21 12- 12
22 31- 31
23 12- 12
24 25- 25
25 31- 31

Updated on: 15-Nov-2021

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements