R Tutorial
Introduction to R | Tutorial Main Menu | Developing Scatterplots
Section 2: Using R for basic calculations
R has a fairly comprehensive set of mathematical functions and relational operators. This section will show you how to assign a value to a variable as well as how to use R like a scientific calculator.
Mathematical Operations and Vectors
NOTE: Variable names are case sensitive in R, so it is very important to understand that X is not the same as x and Y isn't the same as y.
Figure 2-1
Figure 2-2
Here are a few examples of calculations(with their returned results) that can be performed in R:
> 10 + 12
[22]
> 1 + 5 -2/1
[4]
> sum(1,2,3,4,5)
[15]
> median(1:5)
[3]
This is an example of how creating a C function can perform simple subtraction:
> c(2,3,5,7,11,13) - 2
[0 1 3 5 9 11]
Mathmatical Functions
Figure 2-3
Trigonometry(sin,cos and tan) as well as their inverses(asin, acos and atan)
Logarithmic/Exponents(log and exp) and their varients(log1p and expm1)
Assigning Variables
Assigning a variable in R is done by using either <- or =. For example, if we wanted to assign values to x and y, it would appear in R like this:
x <- 5
y = 10
Once these variables are assigned you can use the variables in further calculation:
> x + 2 + y -3
[14]
Special Numbers
R has four special numeric values to help with arithmetic:
Inf Infinity
-Inf Negative Infinity
NaN Stands for "Not a Number"
NA Placeholder for Missing Values
Classes
All variables in R have a class, which tells you what kinds of variables they are. To find out what class a particular variable pertains to, you can use the code: class(my_variable)
These are the types of classes available within R:
"character"
"complex"
"double"
"expression"
"integer"
"list"
"logical"
"numeric"
"single"
"raw"
Creating a String
The character object is used to represent string values in R. To convert objects into character values we would use the as.character() function. Here are the string variables in R:
substr(x)
nchar(x)
toupper(x)
tolower(x)
strsplit(x,y)
paste(...)
To create a string in R, you need to first define the variable and relate it to a given function. Then, you specify what data to return when that variable is referenced. Below is an example of a simple string in R that returns randomized capital and lowercase letters as well as numbers using the variable makerandomstring.
Figure 2-4