R Functions, Part 1

The following are a few simple observations regarding functions in R using this code to demonstrate: [grep(“yellow”, colors())]
This code looks for all colors in the color palette that have the string “blue” in them.
I got this code from: efg’s Research Notes:  Color Chart

Declare a function in R as follows:
myfunctionname <- function(argument1, argument2, …) { }

Note that the arguments are not typed (i.e. they don’t have to be declared for type, for example as integer or string etc. ).  Also, another function with the same name but a different number of arguments can not be created in R.  Thus, default arguments must be used to create a function that takes different arguments.

Therefore, I can make a simple function to look for colors in the color palette.
mycolors <- function(mycolor) { colors()[grep(mycolor, colors())]}

Then to use it, mycolors(“yellow”);
[1] “greenyellow” “lightgoldenrodyellow”
[3] “lightyellow” “lightyellow1”
[5] “lightyellow2” “lightyellow3”
[7] “lightyellow4” “yellow”
[9] “yellow1” “yellow2”
[11] “yellow3” “yellow4”
[13] “yellowgreen”

I could also use this to display some routine general statistics. Although, if more than one output to the screen is needed, then “print” must be used.
For example, the following is an example without he intended results:
helloworld <- function () {hello<-“hello”; world<-“world”;  hello; world;}
[1] “world”
And in the next example, the intended results can be seen:
helloworld <- function () {hello<-“hello”; world<-“world”; print(hello);print(world);}
[1] “hello”
[1] “world”

Useful resource:
R in a Nutshell [Kindle Edition]


This post discussed simple functions examples in R and other observations are welcome in comments of course. It mainly treated a functional view on the R functions rather than R’s Object Oriented view which I haven’t delved into.

Setup information:
2010 13 inch Mac OS X 10.6.8, 8G Ram with R x64 2.15.1 and R studio 0.96.330 running in Windows 7 running in VMware Fusion 3.1.2 (wanting to get more information or test out virtualbox since it was recommended to me)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s