# Doing Simple Math in R

As a mathematical program, R is able to calculate a wide range of mathematical functions. This post will cover some basic operations involving variables and vectors.  We will start with an example, imagine that two basketball players, James and Kevin, have decided to donate money to a local charity forever point they score in a game. James agrees to give \$150.00 per point and Kevin agrees to give \$130.00 per point. This promise is for the last six games they have played. You want to know the following

1. How much money did they give combined for each game?

Below is the code for this scenario.

• ```> points.of.James <- c(12, 15, 30, 25, 23, 32)
> points.of.Kevin <- c(20, 19, 25, 30, 31, 22)
> James.money <- points.of.James * 150
> Kevin.money <- points.of.Kevin * 130
> James.money + Kevin.money
 4400 4720 7750 7650 7480 7660```

Here is what we did

1. We need to know how many points James and Kevin scored in each game. Each of these values were set to their own variable “points.of.James” and “points.of.Kevin” respectively. This information was provided for you.
2. We then needed to figure out how much money James gave away by multiplying his points by the 150.00 per point he promised. This value was assigned to the variable “James.money” We also did this for Kevin but he only promised to pay 130.00 per point. Kevin’s amount was set to the variable “Kevin.money”
3. Finally, we combined the amount James and Kevin promised by adding together the variables “James.money” and “Kevin.money”

Rounding

Numbers can also be rounded in R. Going back to our previous example. Let’s say we want to know how much James and Kevin gave round to the nearest thousand. Below is the code

```> round(James.money + Kevin.money, digits = -3)
 4000 5000 8000 8000 7000 8000```

Here is what happened

1. We used the “round” function to round the number.
2. The variables “James.money” and “Kevin.money were put inside the parenthesis with the operator + put between them so that R adds them together.
3. Since we are rounding, we told are that we want to round to the nearest thousand by adding the argument “digits” with an equal sign followed by negative three. The negative tells R to round by looking to the left three place from the decimal. If we wanted to round to the nearest thousandth we would have used positive 3.

This was just an introduction to some of the basic mathematical functions of R

## 1 thought on “Doing Simple Math in R”

This site uses Akismet to reduce spam. Learn how your comment data is processed.