How I created an R function (for the first time)

calculator-scientific

I know you will probably laugh at me when you read this, especially if you’re a techie, but recently I took my R growth to a new level by creating a proper function. Actually I was experimenting a little with the apply family of functions when it occurred to me that I should attempt to build a function for sapply

First I created a vector of random numbers and created a (probably) meaningless mathematical function

# Create a vector "vec" of random numbers
# and a mathematical function "funny_no"
(vec  <-  round(rnorm(1200, mean = 16, sd = 2)))
funny_no  <-  function(x) sqrt(x)/2 + 3*log10(x) 

 

When I ran it, it worked very well. So I thought to myself “What if I wanted to prevent this function from accepting negative numbers? Well, after a little tinkering, I came up with this:

# Add conditional statements to "funny_no"
funny_no  <-  function(x) {
    if (x>=0) {
      sqrt(x)/2 +3*log10(x)
   }
    else {
      stop("Cannot use negative numbers")
   }
}

And when I ran the following lines of code I saw it was purr-fect!

vec <- round(rnorm(1200, mean = 16, sd = 2))
sapply(vec, funny_no) 

# The next line inserts negative values and function
# throws an error saying "Cannot use negative numbers"
vec[vec == 15]  <-  -15
sapply(vec, funny_no)

So there you have it. Time for some coffee!

Advertisements

Leave a comment

Filed under Computers & Internet

Your comments:

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s