## First, define a few objects to use below.
x <- 2.5
y <- 7
z <- 5
## Show some basic arithmetic operations
y + x[1] 9.5y - x[1] 4.5y * x[1] 17.5y / x[1] 2.8All of the familiar arithmetic operators are available in R. When we do arithmetic on named R objects, the values stored in those objects are used to evaluate the expression.
The following code will add, subtract, multiply, and divide the values stored as y and x.
We use the caret character, ^, to specify exponents. The following code will square and cube the value of y.
The sqrt() function returns the square root of it’s argument (i.e., the value we specify inside the parentheses). The following code calculates the square root of y.
For other roots, we can use fractional exponents.
R also includes many special functions for the most common mathematical operations.
[1] 1.94591[1] 0.845098[1] 2.807355[1] 12.18249[1] 2[1] -3.142[1] -4[1] -3[1] 3.14159Note that log(y) calculates the natural logarithm of y, \(\ln(y)\). If you want the “ordinary” base-10 log, you need to use the log10() function.
age that takes the value of your age in whole years.age object you created in above to create a second object called weeks that takes the value of your age in whole weeks.
age contains 52 whole weeks).weeks.When parsing your commands, R will, mostly, scan each line of code from left to right and apply each mathematical operation according to the usual PEMDAS ordering.
Notice how the following two expressions produce different results.
x by z and then add y to the result.x to y and then divide the result by z.Why do the following two expressions produce different answers?