Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Adapt the addPercent Function in R

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){
 paste(x,"%",sep="")
}

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,...){
 UseMethod("addPercent")
}

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%"
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.