Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to replace . in a string?

Tags:

I have a string say "a.b" and I want to replace "." with "_".

gsub(".","_","a.b")

doesn't work as . matches all characters.

gsub("\.","_","a.b")

Just gives me an error.

Reading the documentation on ?gsub is not that helpful!

So how to do this straight-forward thing?

like image 665
xiaodai Avatar asked Dec 01 '13 07:12

xiaodai


People also ask

How do I replace multiple characters in a string in R?

Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.

How do I remove a specific character from a string in R?

How to remove a character or multiple characters from a string in R? You can either use R base function gsub() or use str_replace() from stringr package to remove characters from a string or text.

How do I replace an element in R?

replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values. It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values.

Is there a Replace function in R?

Replacing values in a data frame is a very handy option available in R for data analysis. Using replace() in R, you can switch NA, 0, and negative values with appropriate to clear up large datasets for analysis.


1 Answers

. matches any character. Escape . using \ to match . literally.

\ itself is also should be escaped:

> gsub("\\.", "_", "a.b")
[1] "a_b"
like image 116
falsetru Avatar answered Sep 21 '22 15:09

falsetru