8 - R Introduction
8 - R Introduction
Introduction to R
Enrico Properzi
[email protected]
R offers plenty of options for loading external data, including Excel, Minitab and
SPSS files. We have included a tutorial titled Data Import on the subject for the
purpose.
Variable Assignment
We assign values to variables with the assignment operator "=". Just typing the
variable by itself at the prompt will print out the value. We should note that
another form of assignment operator "<-" is also in use.
> x = 1
> x
[1] 1
> c(1, 2, 3)
[1] 1 2 3
Comments
All text after the pound sign "#" within the same line is considered a comment.
> 1 + 1 # this is a comment
[1] 2
Getting Help
R provides extensive documentation. For example, entering ?c or help(c) at the
prompt gives documentation of the function c in R. Please give it a try.
> help(c)
There are several basic R data types that are of frequent occurrence in routine R
calculations. Though seemingly innocent, they can still deliver surprises. Instead of
chewing through the language specification, we will try to understand them better
by direct experimentation with the R code.
For simplicity, here, we use only vectors of length one for demonstration.
Numeric
Integer
Complex
Logical
Character
Numeric
Decimal values are called numerics in R. It is the default computational data type.
If we assign a decimal value to a variable x as follows, x will be of numeric type.
> x = 10.5 # assign a decimal value
> x # print the value of x
[1] 10.5
> class(x) # print the class name of x
[1] "numeric"
Integer
> y = as.integer(3)
> y # print the value of y
[1] 3
> class(y) # print the class name of y
[1] "integer"
> is.integer(y) # is y an integer?
[1] TRUE
We can also declare an integer by appending an L suffix.
> y = 3L
> is.integer(y) # is y an integer?
[1] TRUE
Incidentally, we can coerce a numeric value into an integer with the as.integer
function.
Often, it is useful to perform arithmetic on logical values. Just like the C language,
TRUE has the value 1, while FALSE has value 0.
Complex
Logical
Standard logical operations are "&" (and), "|" (or), and "!" (negation).
Character
However, it is often more convenient to create a readable string with the sprintf
function, which has a C language syntax.
> sprintf("%s has %d dollars", "Sam", 100)
[1] "Sam has 100 dollars"
To extract a substring, we apply the substr function. Here is an example showing
how to extract the substring between the third and twelfth positions in a string.
> substr("Mary has a little lamb.", start=3, stop=12)
[1] "ry has a l"
And to replace the first occurrence of the word "little" by another word "big" in the
string, we apply the sub function.
> sub("little", "big", "Mary has a little lamb.")
[1] "Mary has a big lamb."
Vector
Combining vectors
Vectors can be combined via the function c. For examples, the following two vectors
n and s are combined into a new vector containing elements from both vectors.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc", "dd", "ee")
> c(n, s)
[1] "2" "3" "5" "aa" "bb" "cc" "dd" "ee"
Value Coercion
In the code snippet above, notice how the numeric values are being coerced into
character strings when the two vectors are combined. This is necessary so as to
maintain the same primitive data type for members in the same vector.
Vector Arithmetics
> a + b
[1] 2 5 9 15
Properzi Crash course in Statistics 22 / 56
Vector
Similarly for subtraction, multiplication and division, we get new vectors via
memberwise operations.
> a - b
[1] 0 1 1 -1
> a * b
[1] 1 6 20 56
> a / b
[1] 1.000 1.500 1.250 0.875
Recycling Rule
If two vectors are of unequal length, the shorter one will be recycled in order to
match the longer vector. For example, the following vectors u and v have different
lengths, and their sum is computed by recycling values of the shorter vector u.
> u = c(10, 20, 30)
> v = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
> u + v
[1] 11 22 33 14 25 36 17 28 39
Properzi Crash course in Statistics 23 / 56
Vector
Vector index
Negative Index
If the index is negative, it would strip the member whose position has the same
absolute value as the negative index. For example, the following creates a vector
slice with the third member removed.
> s[-3]
[1] "aa" "bb" "dd" "ee"
Out-of-Range Index
If an index is out-of-range, a missing value will be reported via the symbol NA.
> s[10]
[1] NA
Here it shows how to retrieve a vector slice containing the second and third
members of a given vector s.
> s = c("aa", "bb", "cc", "dd", "ee")
> s[c(2, 3)]
[1] "bb" "cc"
Duplicate Indexes
The index vector allows duplicate values. Hence the following retrieves a member
twice in one operation.
Out-of-Order Indexes
The index vector can even be out-of-order. Here is a vector slice with the order of
first and second members reversed.
> s[2:4]
[1] "bb" "cc" "dd"
We now name the first member as First, and the second as Last.
> names(v) = c("First", "Last")
> v
First Last
"Mary" "Sue"
Then we can retrieve the first member by its name.
> v["First"]
[1] "Mary"
Furthermore, we can reverse the order with a character string index vector.
> v[c("Last", "First")]
Last First
"Sue" "Mary"
Matrix
An element at the mth row, nth column of A can be accessed by the expression
A[m, n].
> A[2, 3] # element at 2nd row, 3rd column
[1] 7
> A # print A
col1 col2 col3
row1 2 4 3
row2 1 5 7
Matrix construction
There are various ways to construct a matrix. When we construct a matrix directly
with data elements, the matrix content is filled along the column orientation by
default.
For example, in the following code snippet, the content of B is filled along the
columns consecutively.
> B = matrix(
+ c(2, 4, 3, 1, 5, 7),
+ nrow=3,
+ ncol=2)
Transpose
We construct the transpose of a matrix by interchanging its columns and rows with
the function t .
Combining Matrices
The columns of two matrices having the same number of rows can be combined into
a larger matrix. For example, suppose we have another matrix C also with 3 rows.
> C = matrix(
+ c(7, 4, 2),
+ nrow=3,
+ ncol=1)
Similarly, we can combine the rows of two matrices if they have the same number
of columns with the rbind function.
> D = matrix(
+ c(6, 2),
+ nrow=1,
+ ncol=2)
> rbind(B, D)
[,1] [,2]
[1,] 2 1
[2,] 4 5
[3,] 3 7
[4,] 6 2
Deconstruction
We can deconstruct a matrix by applying the c function, which combines all column
vectors into one.
> c(B)
[1] 2 4 3 1 5 7
List
For example, the following variable x is a list containing copies of three vectors n, s,
b, and a numeric value 3.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc", "dd", "ee")
> b = c(TRUE, FALSE, TRUE, FALSE, FALSE)
> x = list(n, s, b, 3) # x contains copies of n, s, b
List Slicing
We retrieve a list slice with the single square bracket "[ ]" operator. The following
is a slice containing the second member of x, which is a copy of s.
> x[2]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
With an index vector, we can retrieve a slice with multiple members. Here a slice
containing the second and fourth members of x.
> x[c(2, 4)]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
[[2]]
[1] 3
Member Reference
In order to reference a list member directly, we have to use the double square
bracket "[[ ]]" operator. The following object x[[2]] is the second member of x. In
other words, x[[2]] is a copy of s, but is not a slice containing s or its copy.
> x[[2]]
[1] "aa" "bb" "cc" "dd" "ee"
We can modify its content directly.
We can assign names to list members, and reference them by names instead of
numeric indexes.
For example, in the following, v is a list of two members, named "bob" and "john".
> v = list(bob=c(2, 3, 5), john=c("aa", "bb"))
> v
$bob
[1] 2 3 5
$john
[1] "aa" "bb"
List Slicing
We retrieve a list slice with the single square bracket "[]" operator. Here is a list
slice containing a member of v named "bob".
> v["bob"]
$bob
[1] 2 3 5
With an index vector, we can retrieve a slice with multiple members. Here is a list
$bob
[1] 2 3 5
Member Reference
In order to reference a list member directly, we have to use the double square
bracket "[[ ]]" operator. The following references a member of v by name.
> v[["bob"]]
[1] 2 3 5
A named list member can also be referenced directly with the "$" operator in lieu
of the double square bracket operator.
> v$bob
[1] 2 3 5
Data frame
A data frame is used for storing data tables. It is a list of vectors of equal length.
For example, the following variable df is a data frame containing three vectors n, s,
b.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc")
> b = c(TRUE, FALSE, TRUE)
> df = data.frame(n, s, b) # df is a data frame
The top line of the table, called the header, contains the column names. Each
horizontal line afterward denotes a data row, which begins with the name of the row,
and then followed by the actual data. Each data member of a row is called a cell.
To retrieve data in a cell, we would enter its row and column coordinates in the
single square bracket "[ ]" operator. The two coordinates are separated by a
comma. In other words, the coordinates begins with row position, then followed by
a comma, and ends with the column position. The order is important.
Here is the cell value from the first row, second column of mtcars.
> mtcars[1, 2]
[1] 6
Moreover, we can use the row and column names instead of the numeric
coordinates.
> mtcars["Mazda RX4", "cyl"]
[1] 6
Lastly, the number of data rows in the data frame is given by the nrow function.
> nrow(mtcars) # number of data rows
[1] 32
And the number of columns of a data frame is given by the ncol function.
> ncol(mtcars) # number of columns
[1] 11
Preview
Instead of printing out the entire data frame, it is often desirable to preview it with
the head function beforehand.
> head(mtcars)
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
............
We retrieve a data frame column slice with the single square bracket "[ ]" operator.
Numeric Indexing
The following is a slice containing the first column of the built-in data set mtcars.
> mtcars[1]
mpg
Mazda RX4 21.0
Mazda RX4 Wag 21.0
Datsun 710 22.8
............
Name Indexing
We can retrieve the same column slice by its name.
> mtcars["mpg"]
mpg
Mazda RX4 21.0
Mazda RX4 Wag 21.0
Datsun 710 22.8
............
To retrieve a data frame slice with the two columns mpg and hp, we pack the
column names in an index vector inside the single square bracket operator.
> mtcars[c("mpg", "hp")]
mpg hp
Mazda RX4 21.0 110
Mazda RX4 Wag 21.0 110
Datsun 710 22.8 93
............
Numeric Indexing
For example, the following retrieves a row record of the built-in data set mtcars.
Please notice the extra comma in the square bracket operator, and it is not a typo.
It states that the 1974 Camaro Z28 has a gas mileage of 13.3 miles per gallon, and
an eight cylinder 245 horse power engine, ..., etc.
> mtcars[24,]
mpg cyl disp hp drat wt ...
Camaro Z28 13.3 8 350 245 3.73 3.84 ...
To retrieve more than one rows, we use a numeric index vector.
> mtcars[c(3, 24),]
mpg cyl disp hp drat wt ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
Camaro Z28 13.3 8 350 245 3.73 3.84 ...
Properzi Crash course in Statistics 50 / 56
Data frame
Name Indexing
We can retrieve a row by its name.
> mtcars["Camaro Z28",]
mpg cyl disp hp drat wt ...
Camaro Z28 13.3 8 350 245 3.73 3.84 ...
And we can pack the row names in an index vector in order to retrieve multiple
rows.
> mtcars[c("Datsun 710", "Camaro Z28"),]
mpg cyl disp hp drat wt ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
Camaro Z28 13.3 8 350 245 3.73 3.84 ...
Logical Indexing
Lastly, we can retrieve rows with a logical index vector. In the following vector L,
the member value is TRUE if the car has automatic transmission, and FALSE if
otherwise.
> L = mtcars$am == 0
> L
[1] FALSE FALSE FALSE TRUE ...
Data Import
It is often necessary to import sample textbook data into R before you start working
on your homework.
Excel File
Quite frequently, the sample data is in Excel format, and needs to be imported into R prior
to use. For this, we can use the function read.xls from the gdata package. It reads from
an Excel spreadsheet and returns a data frame. The following shows how to load an Excel
spreadsheet named "mydata.xls". This method requires Perl runtime to be present in the
system.
> library(gdata) # load gdata package
> help(read.xls) # documentation
> mydata = read.xls("mydata.xls") # read from first sheet
Alternatively, we can use the function loadWorkbook from the XLConnect package to read
the entire workbook, and then load the worksheets with readWorksheet. The XLConnect
package requires Java to be pre-installed.
> library(XLConnect) # load XLConnect package
> wk = loadWorkbook("mydata.xls")
> df = readWorksheet(wk, sheet="Sheet1")
Table File
A data table can resides in a text file. The cells inside the table are separated by
blank characters. Here is an example of a table with 4 rows and 3 columns.
100 a1 b1
200 a2 b2
300 a3 b3
400 a4 b4
Now copy and paste the table above in a file named "mydata.txt" with a text
editor. Then load the data into the workspace with the function read.table.
> mydata = read.table("mydata.txt") # read text file
> mydata # print data frame
V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3
4 400 a4 b4
For further detail of the function read.table, please consult the R documentation.
> help(read.table)
CSV File
The sample data can also be in comma separated values (CSV) format. Each cell inside
such data file is separated by a special character, which usually is a comma, although
other characters can be used as well.
The first row of the data file should contain the column names instead of the actual data.
Here is a sample of the expected format.
Col1,Col2,Col3
100,a1,b1
200,a2,b2
300,a3,b3
After we copy and paste the data above in a file named "mydata.csv" with a text editor,
we can read the data with the function read.csv.
> mydata = read.csv("mydata.csv") # read csv file
> mydata
Col1 Col2 Col3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3
In various European locales, as the comma character serves as the decimal point, the
function read.csv2 should be used instead. For further detail of the read.csv and read.csv2
functions, please consult the R documentation.
Properzi Crash course in Statistics 55 / 56
Data Import
Working Directory
Finally, the code samples above assume the data files are located in the R working
directory, which can be found with the function getwd.
> getwd() # get current working directory
You can select a different working directory with the function setwd(), and thus
avoid entering the full path of the data files.
> setwd("<new path>") # set working directory
Note that the forward slash should be used as the path separator even on Windows
platform.
> setwd("C:/MyDoc")