  # How to Calculate BMI

Here are some sample code and some simple explanations for what R can do.

R – Functions

Functions are methods of isolating tasks so that they can be repetitively applied. They follow a basic structure.

`name = function(inputs in` `function` `scope){ # function declaration`

` body # Here, There be Dragons!`

` return(output) # spits back the output`

`}`

` # sometime later`

`name(inputs in` `global scope) # function call`

Pass it numeric inputs of height (in inches) and weight (in pounds). It follows the standard formula for BMI, and returns the value.

`BMI = function(height,weight){`

` return(0.45455*weight/(.0254*height)^2)`

`}`

`BMI(71,180)`

Because the contents of the R-function can be done on 1 line without declaring any temporary variables, you can choose to omit the return() statement and define the function on one line. The following code is equivalent to the previous code.

`BMI = function(height,weight){(0.45455*weight/(.0254*height)^2)}`

This returns 25.1765, the BMI for a person who is 71 inches tall and weighs 180 lbs.

If you are so inclined, you could use some properties of more advanced data structures. If you have the height and weight of several people. You can add another column to the data frame using the function.

`h = c(68,70,65,74,69)`

`w = c(185,162,122,224,154)`

`people = data.frame(h,w)`

`people\$bmi = BMI(people\$h,people\$w)`

`print(people)`

So you can run multiple lines through custom functions without iterating between the lines. 