Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last comma in a string

Tags:

regex

r

I have a data.frame. It looks like this:

name    state
Lily    NY
Tom     NY,NJ,
John    PA,NJ
David   SC,PA,NY,
Jim     FL,PA
......

There are more than 100 rows. I just want to remove the last comma in each string if there is. My goal is not to remove all the last character.

like image 236
user2855907 Avatar asked Oct 21 '13 00:10

user2855907


People also ask

How do I remove the last comma in python?

Remove Commas From String Using the re Package in Python In the re pacakge of Python, we have sub() method, which can also be used to remove the commas from a string. It replaces all the , in the string my_string with "" and removes all the commas in the string my_string .

How do I remove the last character of a string?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.


2 Answers

Use a regular expression? Assuming your data frame is DF:

DF$state <- gsub(",$", "", DF$state)

The regular expression ,$ means every comma that occurs at the end of a string. The command gsub replaces every instance of the first argument with the second argument (in this case, nothing) that occurs in the third argument (DF$state).

like image 84
Hugh Avatar answered Sep 23 '22 16:09

Hugh


With R 3.6.0, we can also use trimws with whitespace parameter specifying the ,

DF$state <- trimws(DF$state, whitespace = ",")
DF$state
#[1] "NY"       "NY,NJ"    "PA,NJ"    "SC,PA,NY" "FL,PA"   

data

DF <- structure(list(name = c("Lily", "Tom", "John", "David", "Jim"
 ), state = c("NY", "NY,NJ,", "PA,NJ", "SC,PA,NY,", "FL,PA")),
 class = "data.frame", row.names = c(NA, -5L))
like image 20
akrun Avatar answered Sep 23 '22 16:09

akrun