Docsity

2 R Vectors, Modes and Classes, Summaries of Mathematics

Toggle sidebar
bg1
2 R Vectors, Modes and Classes
To demonstrate modes and classes we also need to introduce the vector object. Vectors consists
of a set of elements that are the same mode (so a vector can consists of number or characters,
but not both). Vectors can also consist of a single value or character. Regardless of the vector
class there are some common uses.
1) All vectors can be created using the concatenate function c() with =or <-, or created
using the function assign().
2) You can concatenate vectors using c().
3) Once created a subset can be access by using the brackets ([]) with the desired indices after
the objects name.
4) The function length() will output how many elements are in the vector.
5) NA indicates a missing element.
Note that if you mix the modes in a vector the vector will cast itself to the highest type. The
hierarchy from lowest to highest is logical, numeric, complex, and character.
The mode is a mutually exclusive classification of the object based on the structure of the
elements. To see an objects mode use mode().
The class is a property that determines how generic function interact with the object. To see an
objects class use class().
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download 2 R Vectors, Modes and Classes and more Summaries Mathematics in PDF only on Docsity!

2 R Vectors, Modes and Classes

To demonstrate modes and classes we also need to introduce the vector object. Vectors consists

of a set of elements that are the same mode (so a vector can consists of number or characters,

but not both). Vectors can also consist of a single value or character. Regardless of the vector

class there are some common uses.

1) All vectors can be created using the concatenate function c() with = or <- , or created

using the function assign().

2) You can concatenate vectors using c().

3) Once created a subset can be access by using the brackets ([]) with the desired indices after

the objects name.

4) The function length() will output how many elements are in the vector.

5) NA indicates a missing element.

Note that if you mix the modes in a vector the vector will cast itself to the highest type. The

hierarchy from lowest to highest is logical, numeric, complex, and character.

The mode is a mutually exclusive classification of the object based on the structure of the

elements. To see an objects mode use mode().

The class is a property that determines how generic function interact with the object. To see an

objects class use class().

1.1 Numeric Mode

The numeric vector is a single entry consisting of an ordered collection of numbers. To set up

a vector named x consisting of five numbers 10.4, 5,6, 3.1, 6.4, and 21.7 use the following

x <- c(10.4, 5,6, 3.1, 6.4, 21.7) # set up vector x x [1] 10.4 5.0 6.0 3.1 6.4 21.

This is an assignment statement using the function c() which in this context can take an

arbitrary number of vector arguments and whose value is a vector created by concatenating the

arguments together.

Notice a few things

i) We assign the value to a variable called x.

ii) When you create an object the object value is not automatically printed out. We see the

output here because we typed the object name on the next line.

iii) The value of x is prefaced with [1]. This indicates that the value is a vector.

iv) Assignments can also be made using the function assign(). The equivalent to what we

did is

assign("x",c(10.4, 5,6, 3.1, 6.4, 21.7))

The usual operator <- can be thought of as a syntactic short cut for the assign()

function.

v) Assignments can also be made in the other direction using - > in the assignment operator,

i.e.

c(10.4, 5,6, 3.1, 6.4, 21.7) -> x

Note that the c() function also works with vectors as in the example below.

1) The standard elementary arithmetic operator of +, -, *, / are used, and ˆ is used for

power.

2) In addition there are several arithmetic functions available.

i) log, exp, sin, cos, tan, sqrt and so on all have their usual meaning (use

the function help to learn more).

ii) sum(x) will return the sum of all the elements in x.

iii) prod(x) will return the product of all the elements in x.

3) Some basic statistical functions.

i) mean(x) calculates the sample mean of the vector x.

ii) var(x) calculates the sample variance of the vector x.

iii) sd(x) calculates the sample standard deviation of the vector x.

A brief example.

x <- c(0,5,9,12,35) length(x) [1] 5 sum(x) [1] 61 mean(x) [1] 12. sd(x) [1] 13.

For complex numbers use i to denote the complex part.

1.2 Character Mode

Character quantities and character vectors are used frequently in R, for example as plot labels.

Where needed they are denoted by a sequence of characters delimited by the double quote

character, e.g., “x-values”, “New iteration results”. Character strings are entered using either

matching double (”) or single (‘) quotes, but are printed using double quotes. The paste()

function takes an arbitrary number of arguments and concatenates them one by one into char-

acter strings. Any numbers given among the arguments are coerced into character strings. The

arguments are separated by default in the result by a single blank character, but this can be

changed by the named parameter, sep=string, which changes it to a specified string.

For example

paste("Georgia","Bulldog") [1] "Georgia Bulldog" x= paste("the value of x is", x) [1] "the value of x is 2" labs <- paste(c("X","Y"), 1:10, sep="") labs [1] "X1" "Y2" "X3" "Y4" "X5" "Y6" "X7" "Y8" "X9" "Y10"

1.3 Logical Mode

Along with numerical and character vectors, R allows manipulation of logical (T/F) quantities.

The elements of a logical vector can have the values TRUE, FALSE, and NA (which means

not available). True and False can be abbreviated T and F respectively, however they are

not reserved words so they can be overwritten by the user. Hence you should use TRUE and

FALSE.

Logical vectors are generated by conditions. For example

temp = x > 13

will set the values of temp to FALSE corresponding to the values of x that are less than 13,

and TRUE to the values of x that are 13 or greater.

The logical operators <, <=, >, >= are similar to what we have seen. == is for strict

equality and != is for inequality. Additionally if c1 and c2 are logical expression c1&&c2 is

the intersection (and), c1||c2 is the union (or), and !c1 is the negation of c1. Logical vectors

may be used in ordinary arithmetic, where they are coerced into numeric values with FALSE

becoming 0 and TRUE becoming 1.

as.character(y) [1] "0" "1" as.numeric(z) [1] NA NA Warning message: NAs introduced by coercion x = c(TRUE,FALSE) y = c(0,1) z = c(’a’,’1’) as.numeric(x) [1] 1 0 as.character(x) [1] "TRUE" "FALSE" as.logical(y) [1] FALSE TRUE as.character(y) [1] "0" "1" as.logical(z) [1] NA NA as.numeric(z) [1] NA 1 Warning message: NAs introduced by coercion

1.5 Factor Class

A factor class allows users to create j indicator variables in one vector, rather than using j

dummy variables (as in Stata or SPSS). R creates this special class from a pre-existing vector

x using the factor() command, which separates x into levels based on the discrete values

observed in x. These values may be either integer value or character strings. For example,

x <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 9, 9, 9, 9) factor(x) # notice levels are printed. [1] 1 1 1 1 1 2 2 2 2 9 9 9 9 Levels: 1 2 9

By default factor() creates unordered factors, which are treated as discrete, rather than

ordered levels. Add the optional argument order=TRUE to order the factors in the vector.

x <- c("like", "dislike", "hate", "like", "don’t know", "like", "dislike")

factor(x, levels = c("hate", "dislike", "like", "don’t know"), ordered = TRUE) [1] like dislike hate like don’t know like dislike Levels: hate < dislike < like < don’t know

If you omit the levels command, R will the order the values alphabetically.

factor(x,order=TRUE) [1] like dislike hate like don’t know like dislike Levels: dislike < don’t know < hate < like

If you omit one or more the levels in the object, R returns level values of NA for the missing

level(s).

factor(x, levels = c("hate", "dislike", "like"), ordered = TRUE) [1] like dislike hate like like dislike Levels: hate < dislike < like

1.6 Index Vectors; Selecting and Modifying Subsets

Subsets of the elements of a vector may be selected by appending to the name of the vector an

index vector in square brackets. More generally any expression that evaluates to a vector may

have subsets of its elements similarly selected by appending an index vector in square brackets

immediately after the expression. Such index vectors can be any of four distinct types.

1) A logical vector

In this case the index vector must be of the same length as the vector from which elements

are selected. Values corresponding to TRUE in the index vector are selected and those

corresponding to FALSE are omitted. For example

x <- c(1:3,NA,4) x [1] 1 2 3 NA 4 l = c(T,T,T,F,T) y <- x[l]

labels.

fruit <- c(5, 10, 1, 20) names(fruit) <- c("orange", "banana", "apple", "peach") fruit orange banana apple peach 5 10 1 20 fruit[c("apple","orange")] apple orange 1 5

The advantage is the alphanumeric names are often easier to remember than numeric in-

dices. This option is particularly useful with data frames, as we will see later.

An indexed expression can also appear on the receiving end of an assignment, in which case

the assignment operation is performed only on those elements of the vector. The expression

must be of the form vector[index vector] as having an arbitrary expression in place of

the vector name does not make much sense here.

The vector assigned must match the length of the index vector, and in the case of a logical

index vector it must again be the same length as the vector it is indexing. For example

x[c(T,T,T,F,T)] <- 0

replaces the fourth index in x by zero and

y[y < 0] <- -y[y < 0]

is equivalent to finding the absolute value of y.

1.7 Generating Regular Sequences

R has a number of facilities for generating commonly used sequences of numbers. For example

1:30 is equivalent to c(1,2,3,.. .,29,30).

The colon operator has high priority within an expression. For example 2*1:15 will create

the vector then multiply the vector by 2. Set n=10 and see the difference between 1:n-1 and

1:(n-1).

The construction 30:1 will generate the sequence backwards.

The function seq() is a more general facility for generating sequences. It has five arguments

which are explained below.

i) from= is the starting value of the sequence.

ii) to= is the stopping value of the sequence.

iii) by= is the increment value.

iv) length.out= determines the length of the sequence. Can be shortened to length

v) along.with= uses the length of the argument to determine the length of the sequence.

Can be shortened to along.

By default seq() will create a single value of 1. seq(10) will generate the sequence

As an example

seq(-5,5,by=.2)

and

seq(length=51,from=-5,by=.2)

generate the exact same vector.

A related function is rep() which can be used to replicate objects in various complicated

ways.

rep(x,times=5)

will put 5 copies of the x vector end to end.

rep(x,each=5)

will repeat each element of x 5 times.

1.8 Missing Values

In some cases the components of a vector may not be completely known. When an element

or value is “not available” or a “missing value” a place within a vector may be reserved for

it by assigning it the special value NA. In general operations are not completed if an NA is