How to Adapt the addPercent Function in R - dummies

How to Adapt the addPercent Function in R

By Andrie de Vries, Joris Meys

Suppose you want to be able to paste the percent sign to character vectors with the addPercent function. A character vector will give an error the moment you try to multiply it, so you need another function for that, like the following:

addPercent.character <- function(x){

Note that the type of the object is not vector but character. In the same way, you also have to rename the original addPercent function to addPercent.numeric in your script.

If you use the system of method dispatching, you can keep all functions in one script file if they aren’t too big. That way, you have to source only one script file in order to have the whole generic system working.

All you need now is a generic addPercent() function like this:

addPercent <- function(x,...){

You use only two arguments here: x and the dots (). The use of the dots argument assures you can still use all the arguments from the addPercent.numeric() function in your call to addPercent(). The extra arguments are simply passed on to the appropriate method via the dots argument.

After sending the complete script file to the console, you can send both character vectors and numeric vectors to addPercent(), like this:

> addPercent(new.numbers, FUN = floor)
[1] "82%" "2%"  "162%" "40%"
> addPercent(letters[1:6])
[1] "a%" "b%" "c%" "d%" "e%" "f%"