Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"replace" function examples

Tags:

r

I don't find the help page for the replace function from the base package to be very helpful. Worst part, it has no examples which could help understand how it works.

Could you please explain how to use it? An example or two would be great.

like image 205
flodel Avatar asked Aug 04 '12 18:08

flodel


People also ask

What is the function for replace?

REPLACE replaces part of a text string, based on the number of characters you specify, with a different text string. REPLACEB replaces part of a text string, based on the number of bytes you specify, with a different text string.

Where is the Replace function in Excel?

To replace text or numbers, press Ctrl+H, or go to Home > Editing > Find & Select > Replace.

What is the syntax of replace function?

The basic syntax of replace in SQL is: REPLACE(String, Old_substring, New_substring); In the syntax above: String: It is the expression or the string on which you want the replace() function to operate.


Video Answer


1 Answers

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)  [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20 

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)  a  b  c  d   1 10  3  4  

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)  a  b  c  d   1  2 10 10  
like image 177
IRTFM Avatar answered Sep 20 '22 20:09

IRTFM