You are on page 1of 11

Data Structures in R

Dr. Mike Brogada - Computational Biology 1


What is Data Structure?
• Collection of data (collection of logical, numeric, integer,
complex, character or raw data)

• Deal with how the data is stored together

• R Data Structures include the Vector, Lists, Matrix,


Arrays, Data Frames and Factors

Dr. Mike Brogada - Computational Biology 2


Vectors
• collection of similar types of objects
• each element must belong to the same data type

• Example:
> vehicles = c("car","bike","bus")
- Creates a vector of character named vehicles
- c means coerce -> values are converted to the simplest type
required to represent all information
- The ordering is logical<integer<numeric<character.

Dr. Mike Brogada - Computational Biology 3


Vector with Consecutive Number
The : operator creates a
vector of consecutive
numbers

The seq() function generates a


sequence of number
Syntax – seq(from, to, by, length.out)
1. from – beginning of the sequence
2. to – end of the sequence
3. by – increment by (default is 1)
4. length.out – length of the sequence
Dr. Mike Brogada - Computational Biology 4
Operators in R
Arithmetic Relational
1. + = Addition 1. <
2. - = Subtraction 2. >
3. * = Multiplication 3. ==
4. / = Division 4. <=
5. %% = Remainder 5. >=
6. ^ = Exponentiation 6. !=

Dr. Mike Brogada - Computational Biology 5


Accessing Vector Elements
• Use [] brackets to access elements, This known as indexing. Indexing
starts with position 1.
• Negative values in the index are used to drop elements
• Boolean values, TRUE or FALSE can be used for indexing

Dr. Mike Brogada - Computational Biology 6


Matrix

Dr. Mike Brogada - Computational Biology 7


Matrix
• Collection of elements of the same data type (numeric,
character, or logical) arranged into a fixed number of
rows and columns.

• Since you are only working with rows and columns,


a matrix is called two-dimensional.

• You can construct a matrix in R with the matrix()


function.

Dr. Mike Brogada - Computational Biology 8


Matrix
Syntax: matrix (data,nrow,ncol,byrow,dimnames)

Data: Elements of a matrix


Nrow: Number of rows
Ncol: Number of columns
Byrow: If TRUE then elements are arranged in a row
Dimnames: Names assigned to rows and columns

Dr. Mike Brogada - Computational Biology 9


Matrix

Dr. Mike Brogada - Computational Biology 10


Accessing Matrix Elements

Dr. Mike Brogada - Computational Biology 11

You might also like