Time for action - creating custom functions

In R, function() can be used to define a custom function, along with its arguments. This allows us to extend the capabilities of R by creating functions that meet our specific needs.

  1. Use function() to define a custom function with arguments:
    > #use function() to define custom function
    > #define our ambush regression model as a custom function in R
    > functionAmbushRating <- function(execution, duration,
    ShuSoldiers, WeiSoldiers) {
    + 56 + 44 * execution -
    + 1.97 * duration +
    + 0.0018 * ShuSoldiers - 0.00082 *
    + WeiSoldiers
    + }
    
  2. Test and verify the function:
    > #what is the predicted rating of an ambush attack in which
    the Shu forces engage 5000 soldiers?
    > functionAmbushRating(probabilitySuccessAmbush,
    meanDurationAmbush, 5000, 5000 * ratioWeiShuSoldiersAmbush)
    [1] 52.746
    
  3. As you can see, our custom function resulted in the same value as our previous calculation. Conveniently, deriving this rating only required us to input the variable values, rather than solving each piece of the equation mathematically.
  4. To further demonstrate our function, suppose instead that our 5,000 Shu soldiers are going to ambush a vulnerable unit of 1,000 Wei soldiers. Calculate the rating of an ambush attack by 5,000 Shu soldiers against 1,000 Wei soldiers:
    > #what is the predicted rating of an ambush attack by 5000 Shu
    soldiers against 1000 Wei soldiers?
    > functionAmbushRating(probabilitySuccessAmbush,
    meanDurationAmbush, 5000, 1000)
    [1] 59.388
    
  5. Under a more predictable and favorable circumstance, our Rating value increased a small amount to 59. Here, we are a little more confident in victory than in our previous scenario, but still far from comfortable.
  6. For a final test, let us examine the performance rating if we are completely certain that our forces will successfully execute the proposed ambush attack. Calculate the rating of a successful ambush attack by 5,000 Shu soldiers against 1,000 Wei soldiers:
    > #what is the predicted rating of a successful ambush attack
    by 5000 Shu soldiers against 1000 Wei soldiers?
    > functionAmbushRating(1, meanDurationAmbush, 5000, 1000)
    [1] 81.388
    

At 81, we are feeling pretty good about our chances for victory. But we must ask ourselves just how likely the proposed circumstances are to occur in an authentic battle situation. Naturally, our prediction is only valid to the extent that we believe that our estimates will reflect actual battle conditions.

What just happened?

We just explored the creation and use of custom functions in R. The ability to create custom functions is a powerful feature that allows you to expand the capabilities of the software to meet your personal needs. Let us discuss the details of custom functions.

function()

In R, the function() command can be used to create custom functions. These can take many shapes and forms. They can also have anywhere from zero to several arguments. The basic format of the function() command is as follows:

function(argument1, argument2,... argumenti) { contents }

Here are some examples of custom functions:

  • No arguments:
    function() { setwd("/Users/johnmquick/Desktop") }
    

    This function sets the working directory to the desktop.

  • One argument:
    function(path) { setwd(path) }
    

    This function sets the working directory to a specified path.

  • Multiple arguments:
    function(path, verify) {
    setwd(path)
    if (verify == TRUE) {
    getwd()
    }
    }
    

    This function sets the working directory to a specified path and then optionally reports that path in the R console.

As we demonstrated in the preceding activity, it is often useful to save a custom function into an R variable. This saves you the effort of retyping the entire command each time you want to execute the function. Furthermore, it allows you to call the function, complete with arguments, using the variable name. These benefits are demonstrated in the following sample code:

> #save a custom function into an R variable
> customFunction <- function(x,y) { 5 * x + 2 * y }
> #call the function by its variable name and solve for x = 1 and
y = 2
> customFunction(1,2)
[1] 9

Note that the parenthesis () are required when you want to execute a function that has been saved into a variable. Without them, the contents of the variable will be displayed in the R console. These differences are demonstrated in the following:

> #without parenthesis, the contents of the function are displayed
> customFunction
function(x,y) { 5 * x + 2 * y }
> #with parenthesis, the function is executed
> customFunction(1,2)
[1] 9

Extended lines

When we created our custom function in step 1 of the previous activity, you may have noticed a new type of console line. These extended lines begin with a plus (+) sign. Unlike input lines that begin with a greater than sign (>) and output lines that have no leading character, extended lines are purely cosmetic. Extended lines are used to format long segments of code so that they are more readable and aesthetically pleasing. The plus sign lets you know that your previous line is being continued. In effect, an extended line is similar to using a hard return in a word processor. The previous line is cut off immediately, while the text continues at the start of the next line. The formatting value of extended lines is clarified by the following sample code:

> #using a single line to define a long function
> functionAmbushRating <- function(execution, duration,
ShuSoldiers, WeiSoldiers) { 56 + 44 * success - 1.97 * duration +
0.0018 * ShuSoldiers - 0.00082 * WeiSoldiers }
> #using multiple lines to define a long function
> functionAmbushRating <- function(execution, duration,
ShuSoldiers, WeiSoldiers) {
+ 56 + 44 * execution -
+ 1.97 * duration +
+ 0.0018 * ShuSoldiers - 0.00082 *
+ WeiSoldiers
+ }

Pop quiz

  1. Which of the following elements is not required when creating a custom function?
    function(argument1, argument2,... argumenti) { contents }
    

    a. function

    b. ()

    c. argument1, argument2,... argumenti

    d. contents

  2. Which of the following is not true of a variable that contains a custom function?

    a. It can be redefined to store a new custom function or other data.

    b. Its function can be called by typing the variable name in the R console.

    c. Its contents can be displayed by typing the variable name in the R console.

    d. Its function can be called by typing the variable name, along with the function's arguments in parenthesis, in the R console.

  3. What does a plus sign (+) at the beginning of an R console line indicate?

    a. The mathematical addition operator.

    b. A line of code that is contained within a custom function.

    c. A single line of code that is being extended across multiple console lines.

    d. Multiple lines of code that are being extended across multiple console lines.

Have a go hero

Now that you are familiar with generating custom functions, use the function() command to recreate the regression equations for each of the remaining battle methods head to head, surround, and fire as R functions. Save each of these custom functions into new variables, named functionHeadToHeadRating, functionSurroundRating, and function0FireRating respectively. Then test each of your functions using the hypothetical battle data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.42.149