R: Data Types Tutorial

In my introduction to R, I covered Lists and Vectors briefly, but I will offer a quick review of them.

Lists

Lists in R are collections of data. These data can be of any type. You can have numbers, letters, and booleans all in a single list if you so choose.

The most important things to remember about lists is that they store any data type and you create them using the syntax: list(data,data,…,data)

dataTy

Vectors

Vectors are a collection of like data types

Here I created 2 vectors – one numeric and one character

syntax: c(data,data,…data1)

dataTy1.jpg

One thing to keep in mind with R is that unlike most programming languages – the indexes in R start at 1.

(1,3) — returns 1rst and 3rd element in vector

(1:3) — returns 1rst through 3rd element

dataTy2

Matrices

A matrix is a multiple dimension vector. All columns must be same length and all elements must be same type.

You shape you matrix by providing row and column size(nrow = and ncol =). You can also name the columns and rows using dimnames=

syntax: matrix (vector, nrow=,ncol=, dimnames=)

dataTy3

Arrays

Arrays allow you to build multi-dimensional arrays. In the example below, I build a 2 dimensional 3×4 array

dataTy4.jpg

Factor

A factor takes a vector and aggregates like items.

As you can see when I print the factor out, it shows all elements in the vector and provides a list of unique elements

nlevels() returns the number of unique elements.

dataTy5

summary() returns a list of the unique elements and a count of items in those elements.

dataTy6

Dataframe

Dataframes allow you to make a tabular table. Also, unlike matrices, the columns in a dataframe can contain different data types

dataTy7

 

 

Please Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s