R Data Objects
There are different types of objects in R. The most used are: vectors, matrices, lists, factors, data frames.
Vectors
In R the simplest data structure is a vector. A vector is defined as an ordered sequence of elements of the same kind.
A vector can be defined according to the data type it contains. Therefore, there are:
- numeric vectors;
- logical (or Boolean) vectors;
- character (or string) vectors.
The most common method to define a vector is the c()
function.
1 2 |
num = c(1, 2, 5.3, 6, -2, 4) num |
1 |
## [1] 1.0 2.0 5.3 6.0 -2.0 4.0 |
1 2 |
char = c("one", "two", "three") char |
1 |
## [1] "one" "two" "three" |
Logical vectors are often defined as the result of control actions on numerical or character vectors.
1 2 |
logic1 = num > 3 logic1 |
1 |
## [1] FALSE FALSE TRUE TRUE FALSE TRUE |
Of course, a logical vector can be created using the c()
function.
1 2 |
logic2 = c(TRUE, FALSE, TRUE) logic2 |
1 |
## [1] TRUE FALSE TRUE |
If a vector mixes different data types, R will store it as a character vector.
1 2 |
mixed = c("foo", 1, TRUE) mixed |
1 |
## [1] "foo" "1" "TRUE" |
The c()
function can be used to create a vector combining several vectors.
1 2 3 4 5 |
vec1 = c(11, 12, 13) vec2 = c(21, 22, 23) vec3 = c(31, 32, 33) comb = c(vec1, vec2, vec3) comb |
1 |
## [1] 11 12 13 21 22 23 31 32 33 |
A vector can be created using sequences. The easiest method is using the operator :
. The inputs of the operator :
are the first number on the left and the last number on the right. The vector will be composed of numbers comprised between the first and the last number (by one unit).
1 2 |
go = 1:20 go |
1 |
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
1 2 |
back = 20:1 back |
1 |
## [1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 |
Other sequences can be created using the seq()
function.
1 2 |
seqby = seq(from = 1, to = 5, by = 0.5) seqby |
1 |
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 |
1 2 |
seqlength = seq(from = 1, to = 5, length = 13) seqlength |
1 2 |
## [1] 1.000 1.333 1.667 2.000 2.333 2.667 3.000 3.333 3.667 4.000 4.333 ## [12] 4.667 5.000 |
Finally, vectors can be created with the rep()
function which repeats the elements of a vector. The first parameter of the rep()
function is the value or vector to be repeated and the second parameter, times
, represents the number of repetitions to be made. Alternatively, the each
parameter enables the repetition of each element of the vector as many times as indicated by the number.
1 |
rep(x = 1 , times = 10) |
1 |
## [1] 1 1 1 1 1 1 1 1 1 1 |
1 |
rep(x = 1:5, times = 3) |
1 |
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 |
1 |
rep(x = 1:5 , each = 3) |
1 |
## [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 |
1 |
rep(x = 1:5 , times = 2 , each = 3) |
1 |
## [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 |
1 |
rep(x = "no", times = 5) |
1 |
## [1] "no" "no" "no" "no" "no" |
1 |
rep(x = c("a", "b", "c"), times = c(3, 2, 1)) |
1 |
## [1] "a" "a" "a" "b" "b" "c" |
1 |
rep(x = c("a", "b", "c"), times = rep(4,3)) |
1 |
## [1] "a" "a" "a" "a" "b" "b" "b" "b" "c" "c" "c" "c" |
A subset of the vector x
can be extracted with x[subscripts]
. The selection can be done in three ways.
- A vector of positive integers indicating the elements of the vector to be extracted.
1 2 |
x = c(1, 4, 2, 5, 6, 8, 6, 9, 10) x[3] |
1 |
## [1] 2 |
1 |
x[1:3] |
1 |
## [1] 1 4 2 |
1 |
x[c(2,4)] |
1 |
## [1] 4 5 |
- A vector of negative integers indicating the elements which must not be extracted.
1 2 |
x = c(1, 4, 2, 5, 6, 8, 6, 9, 10) x[-2] |
1 |
## [1] 1 2 5 6 8 6 9 10 |
1 |
x[-c(2, 5, 7)] |
1 |
## [1] 1 2 5 8 9 10 |
- A Boolean vector indicating the elements to be extracted (
TRUE
) or to be left (FALSE
).
1 2 3 |
x = c(1, 4, 2, 5, 6) y = c(TRUE, TRUE, FALSE, FALSE, TRUE) x[y] |
1 |
## [1] 1 4 6 |
1 |
x[!y] |
1 |
## [1] 2 5 |
The !
symbol identifies the “not” logical operator. The logical operator “not” reverses the logical value of a condition on which it operates.
In this way elements satisfying a logical condition can be extracted. Usually, the logical vectors are obtained as the result of logical expressions.
1 2 3 |
x = c(1, 4, 2, 5, 6, 8, 6, 9, 10) y = x > 5 x[y] |
1 |
## [1] 6 8 6 9 10 |
The logical expression can be defined inside the square brackets, directly.
1 |
x[x > 5] |
1 |
## [1] 6 8 6 9 10 |
The &
symbol identifies the “and” logical operator. The “and” logical operator compare two (or more) logical expression and return TRUE if both are TRUE. The following example returns the x
values greater than 2 but less than 8.
1 |
x[x >= 2 & x <= 8] |
1 |
## [1] 4 2 5 6 8 6 |
The |
symbol identifies the “or” logical operator. The “or” logical operator compare two (or more) logical expression and return TRUE if at least one is TRUE. The following example returns the x
values less than 2 or greater than 8.
1 |
x[x < 2 | x > 8] |
1 |
## [1] 1 9 10 |
Extracting unique values contained in a vector can sometimes be useful. This can be done with the unique()
function.
1 2 |
x = c(1, 2, 1, 1, 2, 3, 3, 2, 1, 2, 2, 3) unique(x) |
1 |
## [1] 1 2 3 |
Matrices
Matrices are generalizations of vectors. Like vectors, matrices need to contain elements of the same kind. This Paragraph introduces numeric matrices.
A matrix can be created using the matrix()
function.
1 |
matrix(1:8, nrow = 2, ncol = 4) |
1 2 3 |
## [,1] [,2] [,3] [,4] ## [1,] 1 3 5 7 ## [2,] 2 4 6 8 |
By default, a matrix is filled by columns. The byrow = T
argument of the matrix()
function fills the matrix by rows.
1 |
matrix(1:8, nrow = 2, ncol = 4, byrow = T) |
1 2 3 |
## [,1] [,2] [,3] [,4] ## [1,] 1 2 3 4 ## [2,] 5 6 7 8 |
Alternatively, a matrix can be created by applying the dim()
function to a vector.
1 2 |
x = 1:8 x |
1 |
## [1] 1 2 3 4 5 6 7 8 |
1 2 |
dim(x) = c(2, 4) x |
1 2 3 |
## [,1] [,2] [,3] [,4] ## [1,] 1 3 5 7 ## [2,] 2 4 6 8 |
Finally, a matrix can be created by joining two or more vectors, both as column vectors (cbind()
function) and row vectors (rbind()
function).
1 2 |
cmat = cbind(1:3, 4:6, 7:9) cmat |
1 2 3 4 |
## [,1] [,2] [,3] ## [1,] 1 4 7 ## [2,] 2 5 8 ## [3,] 3 6 9 |
1 2 |
rmat = rbind(1:3, 4:6, 7:9) rmat |
1 2 3 4 |
## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 4 5 6 ## [3,] 7 8 9 |
The cbind()
and rbind()
functions can be used to join two (ore more) matrices or vectors and matrices.
1 |
cbind(cmat, 10:12) |
1 2 3 4 |
## [,1] [,2] [,3] [,4] ## [1,] 1 4 7 10 ## [2,] 2 5 8 11 ## [3,] 3 6 9 12 |
1 |
rbind(cmat, rmat, cmat) |
1 2 3 4 5 6 7 8 9 10 |
## [,1] [,2] [,3] ## [1,] 1 4 7 ## [2,] 2 5 8 ## [3,] 3 6 9 ## [4,] 1 2 3 ## [5,] 4 5 6 ## [6,] 7 8 9 ## [7,] 1 4 7 ## [8,] 2 5 8 ## [9,] 3 6 9 |
Like vectors, a subset of the matrix x
can be extracted with x[subscripts]
. Subscripts can be:
- a set
[rows, cols]
, whererows
is a vector of row numbers andcols
is a vector of column numbers. Numbers are negative when they indicate a row or column to be excluded. - A number, a vector of numbers or a logical condition. In this case, the matrix is treated as if it were a single vector created by stacked matrix columns.
1 2 |
x = matrix(1:24, nrow = 4, ncol = 6, byrow = T) x[1:2, ] |
1 2 3 |
## [,1] [,2] [,3] [,4] [,5] [,6] ## [1,] 1 2 3 4 5 6 ## [2,] 7 8 9 10 11 12 |
1 |
x[, c(1, 3, 5)] |
1 2 3 4 5 |
## [,1] [,2] [,3] ## [1,] 1 3 5 ## [2,] 7 9 11 ## [3,] 13 15 17 ## [4,] 19 21 23 |
1 |
x[c(1,3), c(1, 4)] |
1 2 3 |
## [,1] [,2] ## [1,] 1 4 ## [2,] 13 16 |
1 |
x[-1, ] |
1 2 3 4 |
## [,1] [,2] [,3] [,4] [,5] [,6] ## [1,] 7 8 9 10 11 12 ## [2,] 13 14 15 16 17 18 ## [3,] 19 20 21 22 23 24 |
1 |
x[1:18] |
1 |
## [1] 1 7 13 19 2 8 14 20 3 9 15 21 4 10 16 22 5 11 |
1 |
x[x >= 3 & x < 12] |
1 |
## [1] 7 8 3 9 4 10 5 11 6 |
Lists
A list is an ordered collection of objects. Each object is a component of the list. Each element of the list can have a different structure. It can be a list itself, a vector, a matrix, an array, a factor or a data frame. A list allows you to gather a variety of (possibly unrelated) objects under one name.
Lists are not usually created by users but are the result of statistical procedures in R.
For example, in its simplest form, the lsfit()
function estimates a least-squares regression.
1 2 3 4 |
x = 1:5 y = c(-0.0921, 0.4543, -0.1473, -0.0235, -0.3923) out = lsfit(x, y) out |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
## $coefficients ## Intercept X ## 0.2833 -0.1078 ## ## $residuals ## [1] -0.2676 0.3867 -0.1071 0.1245 -0.1365 ## ## $intercept ## [1] TRUE ## ## $qr ## $qt ## [1] 0.08985 -0.34096 0.05740 0.42145 0.29289 ## ## $qr ## Intercept X ## [1,] -2.2361 -6.7082 ## [2,] 0.4472 3.1623 ## [3,] 0.4472 -0.1954 ## [4,] 0.4472 -0.5117 ## [5,] 0.4472 -0.8279 ## ## $qraux ## [1] 1.447 1.121 ## ## $rank ## [1] 2 ## ## $pivot ## [1] 1 2 ## ## $tol ## [1] 1e-07 ## ## attr(,"class") ## [1] "qr" |
The output of the function is a list made of four objects called “coefficients”, “residuals”, “intercept” e “qr”. The first element of the list is a vector with intercept and slope. The second element is a vector with the residuals of the model. The third element is a Boolean vector of length one indicating if the model contains the intercept. The fourth element is a list containing the QR matrix decomposition of the independent variables.
Even if rarely used, list()
is the basic function to create a list. Its arguments are the elements of the list.
1 2 3 |
myList = list(vec = 1:7, mat = matrix(1:12, ncol = 3), lis = list(a = 1, b = letters[1:4])) myList |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
## $vec ## [1] 1 2 3 4 5 6 7 ## ## $mat ## [,1] [,2] [,3] ## [1,] 1 5 9 ## [2,] 2 6 10 ## [3,] 3 7 11 ## [4,] 4 8 12 ## ## $lis ## $lis$a ## [1] 1 ## ## $lis$b ## [1] "a" "b" "c" "d" |
The elements of a list can be extracted in three different ways:
- with square brackets;
- with double square brackets;
- with the name of the object inside the list.
In the first case, square brackets can be used to extract a list made of one or more objects. As for vectors, the position of the elements to be included or excluded ought to be specified.
1 |
myList[1:2] |
1 2 3 4 5 6 7 8 9 |
## $vec ## [1] 1 2 3 4 5 6 7 ## ## $mat ## [,1] [,2] [,3] ## [1,] 1 5 9 ## [2,] 2 6 10 ## [3,] 3 7 11 ## [4,] 4 8 12 |
1 |
myList[-3] |
1 2 3 4 5 6 7 8 9 |
## $vec ## [1] 1 2 3 4 5 6 7 ## ## $mat ## [,1] [,2] [,3] ## [1,] 1 5 9 ## [2,] 2 6 10 ## [3,] 3 7 11 ## [4,] 4 8 12 |
1 |
myList[1] |
1 2 |
## $vec ## [1] 1 2 3 4 5 6 7 |
In the second case, double square brackets can be used to extract one object (only) from the list.
1 |
myList[[1]] |
1 |
## [1] 1 2 3 4 5 6 7 |
1 |
myList[[2]] |
1 2 3 4 5 |
## [,1] [,2] [,3] ## [1,] 1 5 9 ## [2,] 2 6 10 ## [3,] 3 7 11 ## [4,] 4 8 12 |
1 |
myList[[3]] |
1 2 3 4 5 |
## $a ## [1] 1 ## ## $b ## [1] "a" "b" "c" "d" |
Please note the difference between myList[1]
and myList[[1]]
. The first argument extracts a list with only the first object contained in myList
; in our case a vector. On the other hand, the second argument extracts the vector, which is the content of the first object of the list.
The third way enables the extraction of the content of an object in the list. The use of the object position in the list, as for double square brackets, is replaced by the use of the object name preceded by the symbol $.
1 |
myList$vec |
1 |
## [1] 1 2 3 4 5 6 7 |
1 |
myList$mat |
1 2 3 4 5 |
## [,1] [,2] [,3] ## [1,] 1 5 9 ## [2,] 2 6 10 ## [3,] 3 7 11 ## [4,] 4 8 12 |
1 |
myList$lis |
1 2 3 4 5 |
## $a ## [1] 1 ## ## $b ## [1] "a" "b" "c" "d" |
Indices for the selection can be combined to extract elements in an object of the list using the above-mentioned methods.
1 |
myList[[1]][1:3] |
1 |
## [1] 1 2 3 |
1 |
myList$mat[3:4, c(1, 3)] |
1 2 3 |
## [,1] [,2] ## [1,] 3 11 ## [2,] 4 12 |
1 |
myList$lis[1] |
1 2 |
## $a ## [1] 1 |
1 |
myList$lis[[1]] |
1 |
## [1] 1 |
1 |
myList$lis$a |
1 |
## [1] 1 |
Factors
A factor is a vector-like object used to specify a discrete classification (grouping) of the components of other vectors of the same length. R provides both ordered and unordered factors.
Factor variables are categorical variables that can be either numeric or string variables. There are a number of advantages to converting categorical variables to factor variables. Perhaps the most important advantage is that they can be used in statistical modeling where they will be implemented correctly, e.g., they will then be assigned the correct number of degrees of freedom. Factor variables are also very useful in many different types of graphics. Furthermore, storing string variables as factor variables is a more efficient use of memory.
Vectors, matrices and lists contain numerical data, characters or logics and are basic objects in R. Factors, on the other hand, are a more complex structure, as they contain both the numerical data vector and the labels associated with each level.
To create a factor variable the factor()
function is used. The only required argument is a vector of values which can be either string or numeric. Optional arguments include the levels
argument, which determines the categories of the factor variable, and the default is the sorted list of all the distinct values of the data vector. The labels
argument is another optional argument which is a vector of values that will be the labels of the categories in the levels
argument. The exclude
argument is also optional; it defines which levels will be classified as NA in any output using the factor variable.
1 2 |
grade = c(3, 4, 2, 2, 4, 1, 1, 4, 2, 2) factor(grade) |
1 2 |
## [1] 3 4 2 2 4 1 1 4 2 2 ## Levels: 1 2 3 4 |
1 2 3 |
gender = c(rep("male", 3), rep("female", 4)) gender = factor(gender) gender |
1 2 |
## [1] male male male female female female female ## Levels: female male |
1 2 3 |
size = factor(c(2, 3, 1, 1, 1, 2, 3, 3), levels = c(1, 2, 3, 4), labels = c("small", "medium", "large", "extra large")) size |
1 2 |
## [1] medium large small small small medium large large ## Levels: small medium large extra large |
Once a vector has been defined, it is always possible to modify the labels of the vector’s levels. This can be done with the levels()
function.
1 2 3 |
size = factor(c(2, 3, 1, 1, 1, 2, 3, 3), levels = c(1, 2, 3), labels = c("small", "medium", "large")) levels(size) |
1 |
## [1] "small" "medium" "large" |
1 2 |
levels(size) = c("S", "M", "L") size |
1 2 |
## [1] M L S S S M L L ## Levels: S M L |
The order
parameter of the factor()
function creates a factor with ordered levels.
1 2 3 4 |
mark = sample(c("D", "C", "B", "A"), 12, replace = T) mark1 = factor(mark) mark2 = factor(mark, levels = c("D", "C", "B", "A"), order = T) mark1 |
1 2 |
## [1] A C A A B D A D A C C A ## Levels: A B C D |
1 |
mark2 |
1 2 |
## [1] A C A A B D A D A C C A ## Levels: D < C < B < A |
The as.numeric()
and as.character()
functions transform a factor into a numeric vector or into a vector whose elements are the levels’ labels.
1 |
as.numeric(size) |
1 |
## [1] 2 3 1 1 1 2 3 3 |
1 |
as.character(size) |
1 |
## [1] "M" "L" "S" "S" "S" "M" "L" "L" |
The elements of a factor can be extracted in the same way as the elements of a vector. The logic conditions on the elements of a factor are referred to the factor’s levels which can be obtained with thelevels()
function.
1 2 3 |
size = factor(c(2, 3, 1, 1, 1, 2, 3, 3), levels = c(1, 2, 3), labels = c("small", "medium", "large")) size |
1 2 |
## [1] medium large small small small medium large large ## Levels: small medium large |
1 |
size[1:5] |
1 2 |
## [1] medium large small small small ## Levels: small medium large |
1 |
size[-4] |
1 2 |
## [1] medium large small small medium large large ## Levels: small medium large |
1 |
levels(size) |
1 |
## [1] "small" "medium" "large" |
1 |
size[size == "medium" | size == "large"] |
1 2 |
## [1] medium large medium large large ## Levels: small medium large |
Data Frames
A data frame in R can be thought of as:
- a generalization of a matrix;
- a list of particular kind.
In the first case a data frame can be thought of as a matrix whose columns can be both factors and vectors of the same length but (possibly) of different types (numeric, character, Boolean).
In the second case, the data frame is a list completely made of either vectors (of any kind) or factors, all with the same length.
From a formal point of view, data frames are not a new type of objects. They are objects of list type and data frame class. From a practical point of view, a data frame is a very well-know structure in statistics. Its different kinds of information are organized in columns, whereas rows represent different types of observational units.
Furthermore, data imported in R from external sources, such as text files, Excel files or databases, is saved in R as data frame-like objects.
To sum up, unless there are have specific needs, data frames in R are the ideal tool for data filing and management.
Data frames are usually imported from external sources but the creation of a data frame object in R might sometimes be needed. The most widespread method to define a data frame is the data.frame()
function. Its inputs are a series of vectors or factors of the same length. The generated object is made of as many columns as input elements.
1 2 3 4 5 |
name = c("James", "Stevie", "Otis", "Bob", "Levon", "Patti", "Karen") height = c(180, 170, 175, 190, 168, 160, 165) gender = factor(c("M", "M", "M", "M", "M", "F", "F")) df = data.frame(name, height, gender, stringsAsFactors = F) df |
1 2 3 4 5 6 7 8 |
## name height gender ## 1 James 180 M ## 2 Stevie 170 M ## 3 Otis 175 M ## 4 Bob 190 M ## 5 Levon 168 M ## 6 Patti 160 F ## 7 Karen 165 F |
Alternatively, the vectors composing the data frame can be defined inside the data.frame()
function itself.
1 2 3 4 5 6 |
df = data.frame( height = c(180, 170, 175, 190, 168, 160, 165), name = c("James", "Stevie", "Otis", "Bob", "Levon", "Patti", "Karen"), gender = factor(c("M", "M", "M", "M", "M", "F", "F")) ) df |
1 2 3 4 5 6 7 8 |
## height name gender ## 1 180 James M ## 2 170 Stevie M ## 3 175 Otis M ## 4 190 Bob M ## 5 168 Levon M ## 6 160 Patti F ## 7 165 Karen F |
The management of character vectors in R requires a detailed explanation. By default, numeric vectors become part of data frames as such, whereas character vectors are transformed into factors whose levels correspond to the vector’s unique values.
This behaviour is surely effective when character vectors represent categorical variables with a definite number of modes, such as education qualification or job.
A character vector can also represent a set of strings which are not necessarily referable to a definite number of modes (e.g. person’s proper names) or to numerous and/or unique modes (e.g. Italian municipalities are about 8,000 and have different names). In this case R’s behaviour becomes a disturbing factor because it tends to transform variables of a different nature into factors.
Unfortunately, there is not an optimal solution to this problem. Much depends on the most used types of variables dealt with by a single user.
This behaviour is managed by the stringsAsFactors
logical parameter.
As already mentioned, the default setting is stringsAsFactors = TRUE
which tells R to transform character vectors into factors inside a data frame; stringsAsFactors = FALSE
does not change character vectors. This parameter can be set both in “local” option with the stringsAsFactors
parameter inside the data.frame()
function and in “global” option with stringsAsFactors
inside the options()
function. Clearly, the “global” option of the stringsAsFactors
lasts for the whole session of work but can be locally modified in any moment in a single call to a function.
There are several ways to extract a subset from a data frame. Data management is not among topics of this introductory manual. Like matrices, data can be extracted using x[subscripts]
where subscripts is a set [rows, cols]
, where rows
is a vector of row numbers and cols
is a vector of column numbers. Numbers are negative when they indicate a row or column to be excluded.
The following code chunk shows how to extract the first, the third and the seventh row from the df
dataframe.
1 |
df[c(1, 3, 7), ] |
1 2 3 4 |
## height name gender ## 1 180 James M ## 3 175 Otis M ## 7 165 Karen F |
The code below shows how to extract the firts and the second column from the df
dataframe.
1 |
df[, c(1, 2)] |
1 2 3 4 5 6 7 8 |
## height name ## 1 180 James ## 2 170 Stevie ## 3 175 Otis ## 4 190 Bob ## 5 168 Levon ## 6 160 Patti ## 7 165 Karen |
Like lists, data can be extracted using x$column
where column is the column name.
1 |
df$height |
1 |
## [1] 180 170 175 190 168 160 165 |
1 |
is.vector(df$height) |
1 |
## [1] TRUE |
The above code returns a vector. To get a data frame, the data.frame()
function can be used.
1 |
data.frame(height = df$height) |
1 2 3 4 5 6 7 8 |
## height ## 1 180 ## 2 170 ## 3 175 ## 4 190 ## 5 168 ## 6 160 ## 7 165 |
1 |
data.frame(height = df$height, name = df$name) |
1 2 3 4 5 6 7 8 |
## height name ## 1 180 James ## 2 170 Stevie ## 3 175 Otis ## 4 190 Bob ## 5 168 Levon ## 6 160 Patti ## 7 165 Karen |
The dim()
function can be used to know the number of rows and of columns of a data frame. The same information can be obtained using nrow()
and ncol()
functions, respectively.
1 |
dim(df) |
1 |
## [1] 7 3 |
1 |
nrow(df) |
1 |
## [1] 7 |
1 |
ncol(df) |
1 |
## [1] 3 |
The str()
function returns the structure of a dataframe. For each variable (column), it shows: the name, the type (numeric, character, factor etc.) and first elements.
1 |
df |
1 2 3 4 5 6 7 8 |
## height name gender ## 1 180 James M ## 2 170 Stevie M ## 3 175 Otis M ## 4 190 Bob M ## 5 168 Levon M ## 6 160 Patti F ## 7 165 Karen F |
1 |
str(df) |
1 2 3 4 |
## 'data.frame': 7 obs. of 3 variables: ## $ height: num 180 170 175 190 168 160 165 ## $ name : Factor w/ 7 levels "Bob","James",..: 2 7 5 1 4 6 3 ## $ gender: Factor w/ 2 levels "F","M": 2 2 2 2 2 1 1 |
The head()
function show the first rows of a data frame. Its use is particularly convenient when data sets are long. iris
is a built in R data set. It contains the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris.
1 |
nrow(iris) |
1 |
## [1] 150 |
1 |
head(iris) |
1 2 3 4 5 6 7 |
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa |
Missing Values, Null Objects and Infinite
In R missing values are represented by the symbol NA
(Not Available).
1 2 |
x = c(4, 1, "a") y = as.integer(x) |
1 |
## Warning: si è prodotto un NA per coercizione |
1 |
y |
1 |
## [1] 4 1 NA |
The above chunk create a vector x
. Vectors will be shown in the next Chapter. The vector contains three values: 4, 1 and the character string “a”. Then, elements of the vector are transformed into integer values.
The character string “a” cannot be transformed, so a NA
value is returned.
To check if data is missing, the function is.na()
can be used.
1 |
is.na(y) |
1 |
## [1] FALSE FALSE TRUE |
The NaN
symbol (Not a Number) represents a missing value obtained as a result of an impossible numerical operation. NaN
can be detected with the function is.nan.
1 |
log(-1) |
1 |
## Warning: Si è prodotto un NaN |
1 |
## [1] NaN |
1 |
sqrt(-4) |
1 |
## Warning: Si è prodotto un NaN |
1 |
## [1] NaN |
1 |
x = log(c(-1, 1, 2)) |
1 |
## Warning: Si è prodotto un NaN |
1 |
x |
1 |
## [1] NaN 0.0000 0.6931 |
1 |
is.nan(x) |
1 |
## [1] TRUE FALSE FALSE |
The NULL
symbol represents the null object in R. NULL
is often returned by expressions and functions whose value is undefined. The is.null()
function returns TRUE
if its argument is NULL
and FALSE otherwise.
1 2 |
x = c() x |
1 |
## NULL |
1 |
is.null(x) |
1 |
## [1] TRUE |
Infinite values are represented by the +Inf
and -Inf
symbols in R.
1 |
log(0) |
1 |
## [1] -Inf |
In the above example, R calculates the limit of the function \(log(x)\) as \(x\) approaches zero.
Summary
In this chapter, we showed the most common object types within R. We introduced the main features of each object type and how get a subset of data. Vector is the “basic” object. You can have a numeric, character or logical vector. Matrices are generalisation of vectors. Lists are more complex data type: they collect in a single object several other objects. A factor is a vector-like object used to specify a discrete classification (grouping) of the components of other vectors of the same length. Data frame is a very well-know structure in statistics. It looks like a matrix, but each column can contain different types of data. Its different kinds of information are organised in columns, whereas rows represent different types of observational units. Now that you know the several object types of R, it’s time to get your data into the mix. In the next chapter, we’ll look how to import data into and export data from R from text files, other programs, and database management systems.