Sunday, January 7, 2018

R Functions

1/7/2018

My last post tried to model the random movement of a point on a line. Although successful, the process can be cleaned. Definitely instead of using two programs, I should just use one. To get there I need to learn more about the R program. I am using R Studio.

I reviewed others to get a better grasp on how to run functions in R. Functions are written as:

name = function (inputs) {the function work} or something like that is the style.

add.it = function(x)
{add = x + 1; return(add)}
add.it(x)

so

add.it = function(x)
{add = x + 1; return(add)}
add.it(1)



What did I just do? The first two lines tells R what to process. The 3rd line is where I placed a number. I changed the color to try to show what I am changing. The first two lines explain to R whatever number I put within the 3rd line ( ), it will add 1 to it. In this case I put 1, and 1 was added to 1 resulting in 2.

This is what I paste into the program:

add.it = function(x)
{add = x + 1
return(add)}
add.it(100)

 This is the return:






This time I used 100. The function added the 1 to 100, and the result was 101.

Now that was wordy and confusing. To sum it up with a better explanation:





#1. In notepad I typed 3 lines for my equation. I copied these lines.
#2. I pasted the copied lines into R Studio.
#3. I pressed enter.
#4. Then I looked in the Global Environment area, it showed functions: add.it.
So this shows the function is stored and ready to go!

Then I started messing around:



What this shows is a complicated way to get the program to add 1. But the power to have the program recall a process in future applications is powerful. Although a simple function here, more complicated functions can be developed, then utilized with ease.

Functions can also be placed within function.


Above, the add.it(2) makes 3; yet it itself is within an add.it, so another is added to make 4.

The idea would be to figure out the simple pieces of a process, then start putting those processes together to form more complex processes. Concepts can be brain stormed to find the smaller parts, the linkages to hold them together, then develop the program to return a result.

Thanks for looking. If you made it this far, you are a real trooper.
Enjoy the day!
Comment if you would like!

No comments:

Post a Comment