Tag Archives: R programming

Data Frames in R: Part II

In this post, we will explore how to create data frames as well as looking at other aspects of using data frames in R. The first example below is a data frame that contains information about fictional faculty members. Our job will be to put this information a data frame and to rename the columns. Below is the example and it will be followed by an explanation.

> Faculty <- c('Darrin Thomas', 'Hank Smith', 'Sarah William')
> Salary <- c(60000, 50000, 53000)
> Hire_Date <- as.Date(c('2015-1-1', '2000-6-1', '2012-9-1'))
> Lecturers.data <- data.frame(Faculty, Salary, Hire_Date)
> str(Lecturers.data)
'data.frame':	3 obs. of  3 variables:
 $ Faculty  : Factor w/ 3 levels "Darrin Thomas",..: 1 2 3
 $ Salary   : num  60000 50000 53000
 $ Hire_Date: Date, format: "2015-01-01" "2000-06-01" "2012-09-01"

Here is what happen

  1. We started by making three different vectors and assigning a variable to each. The variables are ‘Faculty’, ‘Salary’, and ‘Hire_Date’.
  2. We then assigned all three variables to the data frame ‘Lecturers.data’ ‘Faculty’ is a factor vector, ‘Salary’ is a numeric vector, and ‘Hire_Date’ is a date vector. Again, the advantage of data frames is their ability to have several different types of data
  3. We then used the ‘str’ function to see the attributes of the ‘Lecturers.data’ data frame.

There is one small problem with the data frame above. ‘Faculty’ is a factor vector but our original vector for “Faculty’ was a character vector. We want ‘Faculty’ to continue to be a character vector instead of it becoming a factor. The example below shows one way to deal with this small problem.

> Lecturers.data <- data.frame(Faculty, Salary, Hire_Date, stringsAsFactors=FALSE)
> str(Lecturers.data)
'data.frame':	3 obs. of  3 variables:
 $ Faculty  : chr  "Darrin Thomas" "Hank Smith" "Sarah William"
 $ Salary   : num  60000 50000 53000
 $ Hire_Date: Date, format: "2015-01-01" "2000-06-01" "2012-09-01"

By adding the argument ‘stringsAsFactors=FALSE’ it make forces all vectors to not be factors. If you look closely you will see that ‘$ Faculty’ is not a Factor anymore as in the previous example. Instead it is now a ‘chr’ or character variable.

It is also possible to rename column names in a data frame just like in a matrix. For example, let’s say you made a mistake with the ‘Hire_Date’ variable. You did not mean the the date the lecturers were hired but the date they resigned. Below is an example of how to fix this.

> Lecturers.data
        Faculty Salary  Hire_Date
1 Darrin Thomas  60000 2015-01-01
2    Hank Smith  50000 2000-06-01
3 Sarah William  53000 2012-09-01
> names(Lecturers.data) [3] <- 'Resign_Date'
> Lecturers.data
        Faculty Salary Resign_Date
1 Darrin Thomas  60000  2015-01-01
2    Hank Smith  50000  2000-06-01
3 Sarah William  53000  2012-09-01

Here is what happening

  1. We displayed the data frame ‘Lecturers.data’ as a reference point
  2. We noticed that we did not want a column named ‘Hired_Date’ but want to change the name to ‘Resign_Date’
  3. To change the name we use the ‘names’ function to change the name of a column in ‘Lecturers.data’. We specifically tell are to rename the third column by using the subset brackets [3] and assign the name ‘Resign_Date’
  4. We then redisplay the ‘Lecturers.data’ data frame. If you compare this data frame with the first you can see that the third column has been renamed as desired.

This post provided some basic information on developing data frames. We learned how to combine vectors into a data frame, how to change a factor to a character vector, and how to rename a column. Such skills as these are beneficial to anyone who needs to use data frames.

Data Frames in R: Part I

So far we have looked at vectors, matrices, and arrays. One thing these three objects have in common is that they consist of one type of data. In other words, vectors, matrices and arrays contain either numerical or character information but not both at the same time.

Data frames are different. They allow you to have a mixture of information all contained within one place. You can have character data, such as names, and numerical data, such as salaries all in one place. In this post, we will first look at how to convert a matrix to a data frame.

Converting a Matrix to a Data Frame

One of the benefits of converting a matrix to a data frame is that the columns in a matrix become variables in a data frame. This is useful for data analysis at times. In the example below, we will convert the matrix of ‘points.team’ into a data frame.  In order to do this we have to use to new functions the ‘as.data.frame’ function which converts the matrix into a data frame and the ‘t’ function which transposes the rows so that they become the columns. Below is the code for completing this

> points.team
      1st 2nd 3rd 4th 5th 6th
James  12  15  30  25  23  32
Kevin  20  19  25  30  31  22
> team.points.df <- as.data.frame(t(points.team))
> team.points.df
    James Kevin
1st    12    20
2nd    15    19
3rd    30    25
4th    25    30
5th    23    31
6th    32    22

This is what we did

  1. We displayed the matrix ‘points.team’ as a reference. The code for creating this is available here.
  2. We then created the variable ‘team.points.df’ and used two functions to convert the matrix ‘points.team’ to a data frame
    1. ‘as.data.frame’ was used to make the actually data frame
    2. ‘t’ was used to move or transpose the names of the rows in the matrix (James and Kevin) to be the names of columns in the data frame. This gives us two variables (James and Kevin) with six entries (1st-6th) if we had not done this we would have made the example below
      > team.points.df
            1st 2nd 3rd 4th 5th 6th
      James  12  15  30  25  23  32
      Kevin  20  19  25  30  31  22

      In this example, we did not transpose ‘James’ and ‘Kevin’ to be columns. Instead 1st-6th are the variables instead of ‘James’ and ‘Kevin’. For our purposes this does not make sense but it may be appropriate it other situations.

  3. The last step involved displaying the new data frame ‘team.points.df’

Using the ‘str’ function allows you to learn some information about a data frame as in the example below

> str(team.points.df)
'data.frame':	6 obs. of  2 variables:
 $ James: num  12 15 30 25 23 32
 $ Kevin: num  20 19 25 30 31 22

Here is what we now know about our data frame

  • The variable is a data frame (data.frame)
  • It has six observations (6 obs.) which are the points scored by the players in six games
  • There are two variables ‘James’ and ‘Kevin’
  • The variables are numeric (num)

This is just the beginning of our examination of data frames in R. In a future post we will look at making original data frames.

Beyond Vectors: Introduction to Matrices and Arrays in R Part IV

In this post, we will look at how to rename the rows and columns in a matrix. We will also examined how to do the following

  • Name rows and columns in matrices
  • Make an array
  • Basic math in matrices & arrays

Naming Rows and Columns

Renaming rows and columns has a practical use. It allows people to provide meaning and or context to the data they are interpreting. In the example below, we will rename the rows and the columns of the basketball players so that it contains their names as well as what game.

> points.of.James
[1] 12 15 30 25 23 32
> points.of.Kevin
[1] 20 19 25 30 31 22
> points.team <- rbind(points.of.James, points.of.Kevin)
> points.team
                [,1] [,2] [,3] [,4] [,5] [,6]
points.of.James   12   15   30   25   23   32
points.of.Kevin   20   19   25   30   31   22
> rownames(points.team) <- c("James", "Kevin")
> points.team
      [,1] [,2] [,3] [,4] [,5] [,6]
James   12   15   30   25   23   32
Kevin   20   19   25   30   31   22
> colnames(points.team) <- c("1st", "2nd", "3rd", "4th", "5th", "6th")
> points.team
      1st 2nd 3rd 4th 5th 6th
James  12  15  30  25  23  32
Kevin  20  19  25  30  31  22

.Here is what’s going on

  1. We make the variables ‘point.of.James’ and ‘point.of.Kevin’ and display them
  2. We combine ‘point.of.James’ and ‘point.of.Kevin’ into a matrix using the ‘rbind’ function and assign this to the variable ‘points.team’
  3. We then display ‘points.team’
  4. We then rename the rows using the ‘rownames’ function. We replace ‘point.of.James’ and ‘point.of.Kevin’ with ‘James’ and “Kevin’ in the rows. We then display this change in the matrix.
  5. Next we rename 1,2,3,4,5,6 with 1st, 2nd, 3rd, 4th, 5th, & 6th. using the ‘colnames’ function.
  6. Lastly, we display the finished table.

Making Arrays

A vector has one dimension (row), a matrix has two dimensions (row & column), and an array has three or more dimensions (length, width, & height for example). We are not going to cover arrays extensively because it is hard to envision data beyond 3 dimensions. In addition, please remember that all the rules and tricks for vectors and matrices apply towards an array. Below is an example of how to make an array

> array1 <-array(1:48, dim=c(6, 8, 4))
> array1
, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    7   13   19   25   31   37   43
[2,]    2    8   14   20   26   32   38   44
[3,]    3    9   15   21   27   33   39   45
[4,]    4   10   16   22   28   34   40   46
[5,]    5   11   17   23   29   35   41   47
[6,]    6   12   18   24   30   36   42   48

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    7   13   19   25   31   37   43
[2,]    2    8   14   20   26   32   38   44
[3,]    3    9   15   21   27   33   39   45
[4,]    4   10   16   22   28   34   40   46
[5,]    5   11   17   23   29   35   41   47
[6,]    6   12   18   24   30   36   42   48

, , 3

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    7   13   19   25   31   37   43
[2,]    2    8   14   20   26   32   38   44
[3,]    3    9   15   21   27   33   39   45
[4,]    4   10   16   22   28   34   40   46
[5,]    5   11   17   23   29   35   41   47
[6,]    6   12   18   24   30   36   42   48

, , 4

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    7   13   19   25   31   37   43
[2,]    2    8   14   20   26   32   38   44
[3,]    3    9   15   21   27   33   39   45
[4,]    4   10   16   22   28   34   40   46
[5,]    5   11   17   23   29   35   41   47
[6,]    6   12   18   24   30   36   42   48

Here is what is happening

  1. We created ‘array1’ and assigned an array to it that contains numbers 1 to 48 and has 6 rows, 8 columns, and 4 dimensions.
  2. When then have R display the results

To locate values in specific indices you have to add an additional number to the address. For example, if you are looking for 1,1,1 you would go to the first dimension, first row, and first column. Also do not forget how extracting rows and columns re-shuffles the numbering of the remaining rows and columns.

Basic Math in Matrices and Arrays

You can change all the values in a matrix and array. For example, let us say we want to add four points to every game that Kevin and James played. We can do this by using the following code.

> points.team
      1st 2nd 3rd 4th 5th 6th
James  12  15  30  25  23  32
Kevin  20  19  25  30  31  22
> new.points.tream <- points.team+4
> new.points.tream
      1st 2nd 3rd 4th 5th 6th
James  16  19  34  29  27  36
Kevin  24  23  29  34  35  26

What happening

  1. We redisplayed the variable “points. team’
  2. We then create a new variable called ‘new.points.team’ and we told R to add 4 points to every value in the variable ‘points.team’
  3. We display the new table. A closer look will show how every value is 4 points higher in the new table than the results of

Conclusions

This conclude the examinations on matrices and arrays.

Beyond Vectors: Introduction to Matrices and Arrays in R Part III

In this post, we will continue to explore the basic features of matrices. Specifically, we will look at how to replace values in a matrix and how to combine vectors into a matrix.

Replacing Values in a Matrix

There are times when we might input the wrong value into a matrix. The hard way to deal with this problem is to remake the entire matrix. The easy way is to only replace the incorrect value. You can change values by individual index, by row or column or by even importing another matrix (we will not covering replaces values in a matrix with another matrix). Below are examples

> matrix1<-matrix(1:20, ncol=4)
> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> matrix1[1,1] <- 4
> matrix1
     [,1] [,2] [,3] [,4]
[1,]    4    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

In this first example we wanted to replace the value in index 1,1 with the number 4 here is what happened.

  1. We created the matrix ‘matrix1’ using numbers 1-20 (1:20) with 4 columns (ncol = 4).
  2. We type ‘matrix1’ so R displays it. The purpose of this is so that we can compare the original matrix with the modification.
  3. We than type in ‘matrix1’ into R and subset row 1 column 1 using brackets and we assigned the number 4 to row 1 column 1.
  4. We then type ‘matrix1’ to show the modified matrix

If you look carefully at 1,1 in the matrix you will that the value in this index has been changed from 1 to 4.

Below is an example of replace an entire row. This technique can also be used for replacing a column

> matrix1<-matrix(1:20, ncol=4)
> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> matrix1[2, ] <- c(2,3)
> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    3    2    3
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

Here is what happened

  1. We created the matrix ‘matrix1’ and displayed it as a reference
  2. We then subsetted the second row of ‘matrix1’ and told are to put in that row the numbers 2 and 3
  3. We then displayed the modified matrix

If you look carefully, you will see that in the second row we now have the pattern 2,3.  When you tell R to replaces values using a pattern, R will continue to repeat the pattern until the row is filled. Even though we only told R to use two numbers (2 and 3) R filled all four columns in the second row with the pattern 2,3.

Combining Vectors into a Matrix

You can combine two or more vectors into a matrix by using the function ‘rbind’ below is an example.

> points.of.James
[1] 12 15 30 25 23 32
> points.of.Kevin
[1] 20 19 25 30 31 22
> points.of.players <- rbind(points.of.James, points.of.Kevin)
> points.of.players
                [,1] [,2] [,3] [,4] [,5] [,6]
points.of.James   12   15   30   25   23   32
points.of.Kevin   20   19   25   30   31   22

Here is what we did

  1. We redisplayed the values of the variables ‘points.of.James’ and ‘points.of.Kevin’
  2. When then created the variable ‘points.of.players’ and used the ‘rbind’ function to combine the values in the vectors/variables of ‘points.of.James’ and ‘points.of.Kevin’
  3. We then display the results

In a future post, we will examine how to rename the rows and columns so that they provide critical information for people who may be trying to interpret the information.

Beyond Vectors: Introduction to Matrices and Arrays in R Part II

In this post, we will continue to explore the different actions that can be performed when using matrices and arrays. In particular, we will look at how to manipulate the values within a matrix.

Manipulating Values in a Matrix

Before manipulating values it is important to understand what an index is. An index or Indices, which is the plural form, is the address f a value within a matrix. There are two numbers involved in an index. The first number represents the row that the value is in and the second number represents the column. Again this is similar to Microsoft excel and its system for giving every cell an address.

Below is an example to help make this clearer

> matrix1<- matrix(1:20, ncol=4)
> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

Here is what we did,

  1. We made a variable called ‘matrix1’ and this variable has a matrix of 20 consecutive numbers (1:20) with four columns (ncol = 4)
  2. We then print ‘matrix1’ in R

Now for a simple quiz

What value is in row 3 column 2?*

What value is in row 5 column 4?**

The answers are at the bottom of the post.

In R, we do not say ‘row 3’ and ‘column 2’. Instead we would simply say 3, 2 or 5, 4 in the code.

Extracting Values

With our knowledge of indices we can now extract or removes values from a matrix. For example, below is a way to extract and only look at the first two rows and columns two and three of our matrix. In each example, I will display the original matrix and then the extracted matrix so you can compare the differences.

> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> matrix1[1:2, 2:3]
     [,1] [,2]
[1,]    6   11
[2,]    7   12

Here is what happen

  1. We printed matrix1 as a reference for comparison
  2. We then extracted the first two rows (1:2) and the second and third columns (2:3) of ‘matrix1’ using brackets
  3. R then prints the results

Notice how R renames the rows and columns. Rows 1 and 2 are still rows 1 and 2 because we extracted them. However, what use to be rows 2 and 3 has been renamed rows 1 and 2 in the extracted matrix. This can get really confusing so be careful.

If you want to extract an entire row you do not specify the column as in the example below

> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> matrix1[2:3,]
     [,1] [,2] [,3] [,4]
[1,]    2    7   12   17
[2,]    3    8   13   18

Here is what happening.

  1. We print ‘matrix1’ as a reference for comparison
  2. We extract from ‘matrix1’ rows 2 and 3 (2:3) using brackets. Notice that we put a comma after 2:3. This tells R to take the whole row.
  3. R prints the results. Notice what was once rows 2 and 3 is now rows 1 and 2.

You can also remove rows and columns in a matrix as in the example that follows

> matrix1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> matrix1[-2,-3]
     [,1] [,2] [,3]
[1,]    1    6   16
[2,]    3    8   18
[3,]    4    9   19
[4,]    5   10   20

Here is what is going on

  1. We print ‘matrix1’ as a reference.
  2. We then tell R to remove row 2 and column 3 (-2, -3). The removal of a row and or column is indicated through using a negative – sign.
  3. R prints the results. Notice that there are now 4 rows and 3 columns because we remove one row and one column. In addition, don’t forget that the numbers and columns have been renumbered

ANSWERS TO QUIZ

*8

**20

Beyond Vectors: Introduction to Matrices and Arrays in R

Vectors, matrices, arrays, what is the difference? The difference has to do with the number of dimensions that they have. A vector is only only one dimension. Vectors are one row of information. Matrices have two dimensions which are rows and columns. Any Microsoft excel spreadsheet is a matrix of rows and columns and thus contains two dimensions. An array is anything with three or more dimensions such as height, width and depth. Anything beyond three dimensions is hard for the typical mind to grasp.

Creating a Matrix

We will now create a simply matrix below. An explanation is provided after the code

> matrix.1 <- matrix(1:20, ncol=4)
> matrix.1
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

Here is what we did

  1. We created the variable ‘matrix.1’
  2. Within this variable we put a matrix that contain the numbers 1 to 20 (1:20)
  3. When the specified that we want four columns.
  4. R creates the matrix
  5. We type ‘matrix.1’ into R and press enter so we can see the matrix

Once you specify the number of columns R determines the number of rows itself. However, R does not like empty space in the rows and columns. Therefore, you matrix must use all of the space possible within it or you will get the message below.

> matrix.1 <- matrix(1:19, ncol=4)
Warning message:
In matrix(1:19, ncol = 4) :
  data length [19] is not a sub-multiple or multiple of the number of rows [5]

In the example above, I tried to put 19 numbers into a matrix that had 4 columns and 5 rows which equals 20 spaces or indices. Since there was one empty space R did not want to create the matrix.

Examining the Properties of Matrices

If you type in the function “str” you get the following information

> str(matrix.1)
 int [1:5, 1:4] 1 2 3 4 5 6 7 8 9 10 ...

Here is what this information means

  • int means that the matrix contains integers
  • 1:5 means that there are 5 rows and all rows are included in this description
  • 1:4 means that there are 4 columns and all columns are included in this description
  • 1 2 3 4 5 6 7 8 9 10 … is just the first ten indices in the matrix

The “dim” function will tell you the dimensions of the matrix and the “length” function tells you how many indices there are in the matrix. Both are below.

> dim(matrix.1)
[1] 5 4
> length(matrix.1)
[1] 20

The “dim” function indicates we have 5 rows and 4 columns. The ‘length’ function indicates that we have 20 indices.

This serves only as in introduction to matrices. We haven’t really dealt with arrays yet but many of the same ideas and concepts apply equally to them as well.

Introduction to Factors in R

Factors are used in R for data that is categorical. Categorical data is date that does not normally involve numbers but rather descriptions. For example, people can be right or left handed, gender is often defined as male or female. Each of these descriptions are categories with a variable.

To make a factor in R you need to use the “factor” function. Within the “factor” function there are three important arguments which are explained below

  • x–This is the place where the name of the variable containing the vector is placed
  • levels-This is another optional vector of values that x might have taken. If this is confusing it should be.
  • labels-This argument allows you to rename your levels within the factor if you want

In the example below we are going to make a factor that contains several different car manufacturers.

> car.makers <- c("Ford", "Isuzu", "Honda", "Toyota")
> factor(car.makers)
[1] Ford   Isuzu  Honda  Toyota
Levels: Ford Honda Isuzu Toyota

This is what happened

  1. We created the variable ‘car.makers’ and stored the values or names of car makers in the variable using a vector
  2. We used the “factor” function on the variable ‘car.makers’.
  3. R prints the the values in the factor as well as the levels. Notice that the levels and the values are the same.

You can also add labels to a factor. For example, let’s say you wanted to abbreviate the names in the ‘car.makers’ variable by removing vowels. Here is how.

> factor(car.makers, labels=c("Frd", "Isz", "Hnd", "Tyt"))
[1] Frd Hnd Isz Tyt
Levels: Frd Isz Hnd Tyt

All that we did was add the ‘labels’ argument to the “factor” function. We put in are substitute values and we are done.

str() Function

A unique thing about R is that when you look at the structure of the factor using the “str” function you get the following printout.

> str(car.makers)
 Factor w/ 4 levels "Frd","Isz","Hnd",..: 1 3 2 4

This is telling us that the factor ‘car.makers has for levels. R gives us three of them next. After this we get the number 1, 3, 2, 4. What do these numbers mean.

R assigns number to factor levels base on alphabetical order below is a translation of the list above.

  • Ford is the first letter in the list alphabetically so it gets 1
  • Isuzu is second alphabetically and gets 2
  • Honda is next and receives a 3
  • Toyota, which was not listed because R only prints the first three levels is the the last level alphabetically and receives a 4

These numbers can be used to create subsets just as with vectors. Below is another example

> levels(car.makers) [3:4]
[1] "Hnd" "Tyt"

In the example above, we told are that we want the levels of the factor ‘car.makers’. However, we specifically asked for levels 3 and for by using the brackets. R then prints the names of level 3 and 4

This provides some basic understanding on factors.

Finding Text in a Vector in R

This post will cover how to search for text within a vector in R. There are times when you may be working with a lot of information and you want to find a specific piece of information. For example, let’s say you have a list of names that are not in alphabetical order and you want to know how many names start with the letter “E”. To solve this problem, you need to learn how to search text by searching for a pattern. Below is an example of how to do this followed by an explanation.

  • > Student.names
     [1] "Andy"    "Billy"   "Chris"   "Darrin"  "Ed"      "Frank"   "Gabe"    "Hank"   
     [9] "Ivan"    "James"   "Karl"    "Larry"   "Matt"    "Norman"  "Oscar"   "Paul"   
    [17] "Quinton" "Alex"    "Andre"   "Aron"    "Bob"     "Rick"    "Simon"   "Steve"  
    [25] "Thomas"  "Tim"     "Victor"  "Vince"   "William" "Warren"  "Wilson"  "Ted"    
    [33] "Dan"     "Eric"    "Ernest"  "Fred"    "Jim"     "Ethan"   "Lance"   "Mitch"  
    [41] "Pete"    "John"   
    > grep("E",Student.names)
    [1]  5 34 35 38
  1. You have to create the variable ‘Student.names’ and type all the names above as a vector
  2. Next, you use the ‘grep’ function to determine which of the names start with “E” in the variable ‘Student.names’
  3. R tells by position or index which names start with ‘E’

Now you know where the names that start with ‘E’ are but you don’t know the actual names. Below is how you extract the names from the variable.

>  Student.names[grep("E", Student.names)]
[1] "Ed"     "Eric"   "Ernest" "Ethan"

Here is what happened

  1. You told the computer that you want a subset of all the names that start with “E” from the variable ‘Student.names’
  2. You used the ‘grep function to do this.
  3. R returned the names that start with ‘E’

Substituting Text

You can also substitute text in a vector. For example, let’s say you want to replace the name ‘Ed’ in the ‘Student.names’ variable with the more formal name of ‘Edward’ here is how it is done. Just so you know, ‘Ed’ was the 5th name in the list but below it will be replaced with ‘Edward.

> gsub("Ed", "Edward", Student.names)
 [1] "Andy"    "Billy"   "Chris"   "Darrin"  "Edward"  "Frank"   "Gabe"    "Hank"   
 [9] "Ivan"    "James"   "Karl"    "Larry"   "Matt"    "Norman"  "Oscar"   "Paul"   
[17] "Quinton" "Alex"    "Andre"   "Aron"    "Bob"     "Rick"    "Simon"   "Steve"  
[25] "Thomas"  "Tim"     "Victor"  "Vince"   "William" "Warren"  "Wilson"  "Ted"    
[33] "Dan"     "Eric"    "Ernest"  "Fred"    "Jim"     "Ethan"   "Lance"   "Mitch"  
[41] "Pete"    "John"
  1. In this example, we used the ‘gsub’ function to replace the name ‘Ed’ with ‘Edward
  2. Using ‘gsub’ we tell R to find ‘Ed’ and replace it with ‘Edward in the variable ‘Student.names’
  3. R completes the code and prints the list as seen above

Hopefully, the information provided will give you ideas into using text in R

Introduction to Character Vectors in R

Vectors in R can be used to store characters or text data. This post will go over some basic ways you can use character vectors.

You create character vectors in much the same way as numeric vectors. The only main difference is that you put quotes ” ” around the words. The quotes tell R that the information within the quotes is text and not numeric information. Below is an example of the creation of a character vector consisting of the names of students.

  • > student.names <- c("Andy", "Billy", "Chris", "Darrin", "Ed", "Frank", "Gabe", "Hank", "Ivan", "James", "Karl", "Larry", "Matt", "Norman", "Oscar", "Paul", "Quinton")
    > student.names
     [1] "Andy"    "Billy"   "Chris"   "Darrin"  "Ed"      "Frank"   "Gabe"    "Hank"   
     [9] "Ivan"    "James"   "Karl"    "Larry"   "Matt"    "Norman"  "Oscar"   "Paul"   
    [17] "Quinton

In this example, we assigned the ‘student.names’ variable to the names and then we typed the variable named ‘student.names’ so that R would print the results.

Subsetting Values

A subset is the result of pulling some information from a larger vector. This is useful if you want to work with a piece of data from a larger data set. For example, let’s say you only want the fourth name from the ‘student.names’ variable to do this an example is provided.

  • > student.names[4]
    [1] "Darrin"

All you did in the example above was type in the variable ‘student.names’. Next you placed in brackets [ ] the number four. This tells R you only want the information in the fourth index of the vector. R then prints the result with the fourth name of the vector.

The possibilities with subsets are endless. For example, you can ask for a sequence of indicies using a colon as shown in the example below where we ask for the fourth through eighth names in the vector.

> student.names[4:8]
[1] "Darrin" "Ed"     "Frank"  "Gabe"   "Hank"

Creating and Assigning Named Vectors

Vectors can be assigned to other vectors. This is used when you need to combine information from different vectors in a way that certain information is linked with certain information. For example, what if you want to combine the students’ names with their test scores? Below is an example of how to do this.

> student.names <- c("Andy", "Billy", "Chris", "Darrin", "Ed", "Frank", "Gabe", "Hank", "Ivan", "James", "Karl", "Larry", "Matt", "Norman", "Oscar", "Paul", "Quinton")
> test.scores <- c(85, 90, 80, 95, 60, 55, 72, 88, 71, 82, 62, 58, 89, 76, 64, 79, 88) 
> names(test.scores) <- student.names 
> test.scores  
    Andy Billy Chris Darrin Ed Frank Gabe Hank Ivan James Karl 
     85     90    80   95    60 55    72    88  71    82  62 
    Larry Matt Norman Oscar Paul Quinton 
     58    89   76      64   79    88

Here is what happened. NOTE: Each name should have a number under it. The formatting is difficult in WordPress sometimes

  1. We created are ‘student.names’ variable.
  2. We created are ‘test.scores’ variable.
  3. We then assigned the names or values in ‘test.score’ to the variable ‘student.names’. This  basic gives a name to every value in the ‘test.score’ variable. In other words, the first value 85 now has the name Andy, the second value 90 now has the name Billy.
  4. You now type ‘test.scores’ again to print the new combined vector.

Now every score has a named associated with it. Think of the name as another form of identification. You can subset information using the index or the name as shown below.

> test.scores["Andy"]
Andy 
  85 
> test.scores[1]
Andy 
  85

Both examples above give you the score for the first index which is 85.

This is just an introduction to character vectors. Keep in mind that much of this information applies to numeric vectors as well.

Introduction to Vectors Part III: Logical Vectors and More

Logical vectors are vectors that compare values. The response R gives is either TRUE which means that the comparision statement is correct or FALSE which means the comparision statement is incorrect.

Logical vectors use various operators that indicate ‘greater than’, ‘less than’, ‘equal to’, etc. As this is an abstract concept, it is better to work through several examples to understand.

You want to know how many times James scored more than 20 points in a game. to determine this you develop a simple equation that R will answer with a logical vector

  • > points.of.James <- c(12, 15, 30, 25, 23, 32)
    > points.of.James
    [1] 12 15 30 25 23 32
    > points.of.James > 20
    [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE

Here is what we did

  1. We inputted the values for ‘points.of.James
  2. We then entered the equation ‘points.of.James > 20’ which means which values in the variable ‘points.of.James’ are greater than 20′.
  3. R replied by stating that the first to values are not greater than 20, which is why they are FALSE and that the last 4 values are greater than 20, which is why they are TRUE.

Logical vectors can also be used to compare values in different vectors. This involves the use of the function ‘which(). The function which() is used for comparing different vectors. Below is an example

You want to know which games that James scored more points than Kevin. Below is the code for doing this

  • > points.of.James <- c(12, 15, 30, 25, 23, 32)
    > points.of.Kevin <- c(20, 19, 25, 30, 31, 22)
    > the.best <- points.of.Kevin < points.of.James 
    > which(the.best) 
    [1] 3 6

Here is what happen

  1. You set the values for the variables ‘points.of.James’ and ‘points.of.Kevin’
  2. You create a new variable called ‘the.best’. In this variable you set the equation that compares when Kevin scored less than James by comparing the values in the variable ‘points.of.Kevin’ with ‘points.of.James
  3. You then used the ‘which()’ function for it to tell which times that Kevin scored less than James.
  4. R responds by telling you that Kevin scored less than James the 3rd time and 6th time

You can also find not each time that Kevin scored less than James but instead find out how many times Kevin scored less than James by using the ‘sum()’ function instead of the ‘which()’ function.

> points.of.James <- c(12, 15, 30, 25, 23, 32)
> points.of.Kevin <- c(20, 19, 25, 30, 31, 22)
> the.best <- points.of.Kevin < points.of.James 
> sum(the.best)
[1] 2

R explains that Kevin scored less than James two times.

Naturally, there is much more that can be done with vectors than what was covered here. This is just a glimpse at what is possible.

Introduction to Vectors in R: Part II

In a previous post, we took our first look at vectors and their use in R. In this post, we will build on this knowledge by learning more ways to use and analyze vectors.

Functions for Analyzing Vectors

An important function for analyzing vectors is the str() function. This function allows you to look at the structure or characteristics of any object, including vectors. Objects are the pieces of data you create and or manipulate in R.

We are going to analyze the structure of the variable ‘points.of.James’, which contains a vector. Below is the code for this followed by an explanation.

  • > points.of.James > str(points.of.James)
     num [1:6] 12 15 30 25 23 32

Here is what we did

  1. We created the variable ‘points.of.James’
  2. We assigned the values 12, 15,30, 25, 23, 32 to the variable ‘points.of.James’ Using a vector
  3. We used the str() function to analyze the variable ‘points.of.James’
  4. The output told us the following
    1. num means that the vector is numeric
    2. 1:6 shares two pieces of information. The 1 tells us how many dimensions the example, which is one. The six tells us how many values or indices the vector has, which is six. In other words there are six numbers in the variable. Remember the word ‘indices’, which refers to the location of a value within a vector, as it will be important in the future.

Let’s say you are curious to know how many indices a vector has. To figure this out you use the length()  function is demonstrated below.

  • > points.of.James > length(points.of.James)
    [1] 6

You can probably see that the variable ‘points.of.James’ has six values within it.

Another useful function for vectors is the ability to combine them. In the example below, we will combine the variables ‘points.of.James’ and ‘points.of.Kevin’.

  • > points.of.James > points.of.Kevin 
    > all.points > all.points  
    [1] 12 15 30 25 23 32 20 19 25 30 31 22

Here is what happen

  1. We made the variables ‘point.of.James’ and ‘points.of.Kevin’ and inputted the values
  2. We created a new variable called ‘all.points’ and assigned the variables ‘points.of.James’ and ‘points.of.Kevin’ to it.
    1. NOTE: Assigning a variable to another variable means assigning the values of the first variable to the second one. In other words, the values of ‘points.of.James’ and the values of ‘points.of.Kevin’ are now stored in the variable ‘all.points’
  3. We then read the ‘all.points’ variable and it showed us all of the values within it. Which the same values found with ‘points.of.James’ and ‘points.of.Kevin’.

One last useful tool when using vectors is the ability to extract values from a vector. This can be done by using the brackets or [ ]. Extracting values means taking a handful of values from a vector and looking at them alone. Below is an example.

  • > all.points
     [1] 12 15 30 25 23 32 20 19 25 30 31 22
    > all.points[10]
    [1] 30

In the example above we were looking at our ‘all.points’ variable. I typed all.points[10] into R and this told R to do the following

  • Extract the tenth value from the ‘all.points’ variable

R then replies by telling me the tenth value of the ‘all.points’ variable is 30.

Off course, you can extract multiple values as seen below

  • > all.points
     [1] 12 15 30 25 23 32 20 19 25 30 31 22
    > all.points[c(2, 4, 6, 8)]
    [1] 15 25 32 19

In this example, we extracted the second, fourth, sixth, and 8th value from the variable ‘all.points’

This is still just an introduction into how vectors can be used in R.

Doing Simple Math in R

As a mathematical program, R is able to calculate a wide range of mathematical functions. This post will cover some basic operations involving variables and vectors.

We will start with an example, imagine that two basketball players, James and Kevin, have decided to donate money to a local charity forever point they score in a game. James agrees to give $150.00 per point and Kevin agrees to give $130.00 per point. This promise is for the last six games they have played. You want to know the following

  1. How much money did they give combined for each game?

Below is the code for this scenario.

  • > points.of.James <- c(12, 15, 30, 25, 23, 32)
    > points.of.Kevin <- c(20, 19, 25, 30, 31, 22)
    > James.money <- points.of.James * 150
    > Kevin.money <- points.of.Kevin * 130
    > James.money + Kevin.money
    [1] 4400 4720 7750 7650 7480 7660

Here is what we did

  1. We need to know how many points James and Kevin scored in each game. Each of these values were set to their own variable “points.of.James” and “points.of.Kevin” respectively. This information was provided for you.
  2. We then needed to figure out how much money James gave away by multiplying his points by the 150.00 per point he promised. This value was assigned to the variable “James.money” We also did this for Kevin but he only promised to pay 130.00 per point. Kevin’s amount was set to the variable “Kevin.money”
  3. Finally, we combined the amount James and Kevin promised by adding together the variables “James.money” and “Kevin.money”

Rounding

Numbers can also be rounded in R. Going back to our previous example. Let’s say we want to know how much James and Kevin gave round to the nearest thousand. Below is the code

> round(James.money + Kevin.money, digits = -3)
[1] 4000 5000 8000 8000 7000 8000

Here is what happened

  1. We used the “round” function to round the number.
  2. The variables “James.money” and “Kevin.money were put inside the parenthesis with the operator + put between them so that R adds them together.
  3. Since we are rounding, we told are that we want to round to the nearest thousand by adding the argument “digits” with an equal sign followed by negative three. The negative tells R to round by looking to the left three place from the decimal. If we wanted to round to the nearest thousandth we would have used positive 3.

This was just an introduction to some of the basic mathematical functions of R

Basics of Vectors Functions in R

Vectors were discussed in a previous post. In short, vectors are a collection of information. Functions serve the purpose of performing several operations one after another. Now, will combine these two concepts into what are known as vectorized functions. Vectorized functions are functions that perform several operations on a vector. In other words, you can put several numbers into a vector and then have a function do something to all the numbers at the same time.

Here is an example

You have been asked to keep score during basketball season. Below are the number of points per game for a player name James for his first six games. The information is inputted in R as follows

  • > points.of.James <- c(24, 8, 8, 12, 18, 9)
    > points.of.James
    [1] 24 8 8 12 18 9

What we have done so far is create the variable “points.of.James” and assigned the vector of 24, 8, 8, 12, 18, 9. The points represent the number of points he scored in the six games.

The first function we are going to use is the sum() function. This function will add up how many points James scored in the six games. Below is the code for it.

  • > sum(points.of.James)
    [1] 79

Here is what we did

  1. We told R we want the sum of the values in the variable “points.of.James”
  2. The values in the variable “points.of.James” are the vector 24, 8, 8, 12, 18, 9.
  3. R adds the values up and produces the answer 79

Another more complicated example has to do with how functions can combine vectors. For example, let’s say a list of people in the English department and you want to add after their name that they all have the position of lecturer. To do this you need to use the paste() function which will combine the information. Below is an example of how to do this using R.

  • >  faculty.names <- c("Darrin Thomas", "John Williams", "Sarah Smith")
    >  Rank <- "Lecturer"
    >  Rank <- ", Lecturer"
    >  paste(faculty.name, Rank, sep = "")
    [1] "Darrin Thomas, Lecturer" "John Williams, Lecturer" "Sarah Smith, Lecturer"

Here is what we did.

  1. We created a variable called “faculty.names” and we assigned a vector to it that contain the following names
    1. Darrin Thomas
    2. John Williams
    3. Sarah Smith
  2. When then created a variable called “Rank” and assigned the value “, Lecturer”. We put the comma in front of the word Lecturer so that when we combine the faculty.names and rank variables we have a comma after the name of the faculty person and before their rank, which is lecturer.
  3. Next, we combined all of the names of the faculty members with the rank of “Lecturer” using the paste() function.
    1. NOTE: In the paste function we included the argument sep = “” This prevents a space appearing after the name of the person when the comma is inserted. Below is an example of what we do not want
      1. Darrin Thomas , Faculty   (Remeber we do not want this space. That’s why we use the sep = “” argument because it removes the space in front of the comma)
  4. After setting up the paste function we get the “faculty.names” and “Rank” combined which shows the names of the faculty members with their corresponding rank.

Let’s pretend you are dealing with the same problem but now the faculty members have different rankings. Here is the code for how to do this.

  • > faculty.names <- c("Darrin Thomas", "John Williams", "Sarah Smith")  
    > faculty.ranks <- c(", Lecturer", ", Senior Lecturer", ", Principal Lecturer")
    > paste(faculty.names, faculty.ranks, sep="")
    [1] "Darrin Thomas, Lecturer" "John Williams, Senior Lecturer"  
    [3]"Sarah Smith, Principal Lecturer"

All that is new is that we created a variable called “faculty.ranks”, which included the new rankings. Then we used the paste function to combine the names with ranks. As you can see, each person can their corresponding rank. The first name got the first rank, the second name got the second rank, etc. If there is a difference between the number of names and ranks R will recycle values to complete the function

Sourcing Script in R

Sourcing a script has to do with having R running several commands either one after another with stopping. In order to do this R Studio, you need to type your code into Source Editor which is normally at the top left-hand side of the program. We are going to go through an example in which R will ask a question and you will answer it.

In the source editor, type the following information. At the end of each line, press enter to move to the next line. I will explain the meaning of the text after the example

h <- "Welcome to R"
yourname <- readline("What is your name?")
print(paste(h, yourname))

After typing this information, you should click on the source button near the top middle of the computer screen. If this is done correctly you should see the following in the console.

> source('~/.active-rstudio-document')
What is your name?

Type your name in response to the question and press enter. Then you should see the following.

> source('~/.active-rstudio-document')
What is your name?Darrin
[1] "Welcome to R Darrin"

So what exactly did we do?

  1. We made a variable named h and assigned the object “Welcome to R”
  2. Next, we made a variable called yourname and assigned the function readline to read the phrase “What is your name?”. The readline function literally reads text.
  3. We then told R to print a combination (using the paste function) of the h variable first (Welcome to R) and the yourname variable second (What is your name?)
  4. Next, we clicked the source script button
  5. In the console, we were asked the question “What is your name?”
  6. We responded with our name.
  7. R takes your name and combines it with the h variable to create the following phrase
  8. “Welcome to R Darrin”

Several steps of code were run at once through using the script editor. This same process could have been done in the console but using the script editor saves time. Many aspects of programming focus on saving time and improving efficiency. There are always several ways to do something but the goal is always to find the method that takes the least amount of effort and improves the readability of the code.

Making and Using Variables in R

Variables are used in R to store information for computational purposes. It seems that there is almost no limit to what can be stored in a variable. To make a variable, you need to know the following information.

  • The name you want to give the variable
  • The information you want to store in the variable

Here is an example,

You want to make a variable that will store the following test score: 80, 81, 82, 83, 84, 85. You want to call the variable test_scores. Here is what we know

  • The name of the variable is test_scores
  • It will contain the values of 80, 85, 90, 95, 100

Here is how this would look in R.

  • > test_score <- 80:85

There are a few things to explain

  1. the <- sign means “assigned to” in other words, the variable name on the left of the <- sign is being assigned to the values 80:85.
  2. The colon sign stands for a sequence. We wanted all whole numbers from 80 to 85 and the colon sign provides this information.
  3. Both the <- and : are known as operators in R. Operators symbols you place between numbers in order to make a calculation.

Know, type test_scores into the R console and press enter. You should see the following.

  • > test_scores
    [1] 80 81 82 83 84 85

R now shows you everything that is stored in the variable. We can also created other variables and perform calculations through the use of variables. For example, let’s say that you want to add 5 points of extra credit to the scores of the test. To do this let’s make a variable called extra_credit and add test_scores to extra_credit

  • > extra_credit <- 5
    > test_scores + extra_credit
    [1] 85 86 87 88 89 90

As you can see, R took the values of test_scores and add extra_credit to each value in test_scores.  This is much faster than entering each value separately to calculate it. We can also make a new variable for the new scores and we can call it revised_test_scores Let’s try

  • > revised_test_scores <- test_scores + extra_credit
    > revised_test_scores
    [1] 85 86 87 88 89 90

Variables can also be used for text. The only difference is that you must put quotes around the words. Otherwise, the computer will think the words are numbers, which does not make sense. Below is an example,

  • > h <- "Howdy"
    > h
    [1] "Howdy"

Lastly, variables can be used to store vectors. This is very useful in saving a lot of time in performing calculations. We will now  make the variable student_names and assigned a vector to it containing the names of students.

  • > student_names <- c("David", "Edward", "John")
    > student_names
    [1] "David" Edward" "John"

This is only the beginning of some of the amazing features of R.

Introduction to Vectors in R

A key component of R is the use of vectors. Vectors a single piece of information that contents a collection of information. This probably sounds extremely confusing so an example will be provided.

Think of an organization such as a school. We will call the school Asia International School. Asia International school consist of an administrator named Dr. T, teachers named Mr. Bob and Mrs . Smith, and students named Sam, David, and Mary. In this example, the school is consider a vector or a single piece of information (Asia International School). The administrators, teachers, and students are the collection of information within the large piece of information that is the school.

If we wanted to write this example using the R programming language it would look something like the following…

  • > Asia International School(Dr. T, Mr. Bob, Mrs. Smith, Sam, David, Mary)
    [1] Dr. T Mr. Bob Mrs. Smith Sam David Mary

To be fair this is not exactly how it is done this is strictly an imperfect illustration of a very abstract concept.

A Real Example

In order to make a vector in R you need to use c() function. A function is a piece of code that does something to the information that is within its parentheses. For example, let’s make a vector that contains the numbers 1, 2, 3, 4, 5.

  • > c(1,2,3,4,5)
    [1] 1 2 3 4 5

To get the second line you need you press enter

The c means combine. The information inside the parentheses is the information that is being combined into one vector. Going back to our school example, Dr. T, Mr. Bob, Mrs. Smith, Sam, David, and Mary were being combined into the school Asia International. In a vector, all information inside the parentheses is known as arguments.

Conclusion

This is just some of the most basic ideas about vectors. There is a great deal more to explore about the use of vectors which is considered one of the most powerful features of R. The challenge of learning R is with the abstract nature of programming. You have to think of things you want to do in terms of a code that the computer can understand. This is very confusing for most people.

Using R

The R program can be used only to process many different mathematical functions. However, many people choose to use some sort of editing tool while using R. The editing tool provides a place for developing and save codes and functions.

There are many different editing tools available. For Windows, a popular choice is RGui. For Mac, R.app is a common choice. The choice that is quickly becoming the standard for R Users is RStudio. RStudio works on all software platforms. This provides a consistent interface for people despite whatever operating system they are using. Below are some additional benefits of RStudio.

  • Brackets are automatically setup when developing code
  • Different parts of a code have a corresponding color. This helps in reading the code.
  • Code completion. Saves time

Coding in RStudio

The first thing people often do when learning to code is create the message “Hello World.” To do this in RStudio requires the following

  1. In RStudio make sure the cursor is blinking in the console section (The console is normally in the lower left hand part of the window)
  2. Type the following and press enter
    1. print (“Hello World!”)
  3. After pressing enter you should see the following
    1. [1] “Hello World!”

Congrats, you have just developed and implemented your first R Script

Doing Some Math

R can be used for performing math calculations as well. Consider the following example

  1. Type the following into the console and press enter
    1. 1 + 3 + 5 + 7
  2. You should get the following output
    1. [1] 16

Have some fun playing with the print as well as calculating various math problems as well.

The History and Characteristics of R

R is a programming language and software environment that is used for the development of graphic data products and the computation of many forms of mathematics. The history of R goes back about 20-30 years ago. This post will look at the history of R as well as the Characteristics of this software.

The History

Ross Ihaka and Robert Gentleman are the developers of R. R is actually based on an older programming language known as S which goes back to the 1970″s. Ihaka and Gentleman develop their own programming language while working together in New Zealand. With the release of R in the early 1990’s, several people joined the project to help to improve it. By 1995, the software had become “open-sourced” which means that anyone can use and modify it for themselves without cost. By 2000, the first version of R (1.0) was released to the public.

Characteristics of R

In many peoples opinion, the best feature of R is the price. Being free, R is by far one of the best softwares for statistical analysis is price is the most important criterion. SPSS and SAS are also great and user-friendlier, however, their price is completely outlandish for most individual researchers. R removes this problem completely

R also has an active community around it that supports its development. For example, people are able to develop packages that provide assistance in running various task in the R software. Naturally, most packages are free as well. The focus on community has enabled R to be run on almost any operating system as well, such as Windows, OSX, or Linux.

R also allows people to make graphs and data products. The graphs are actually very well made. The drawback is understanding the coding necessary to develop these various products. This is discussed more below.

One major drawback that affects the typical computer user is learning the programming language of R. This can be challenging for those who are not techie or able to think abstractly in computer codes. I have never seen a satisfactory way to get around this problem but to crack open a book and practice, practice, practice. With time, the code will start to make sense but it is not a five-minute process for someone who has not studied programming.

Conclusion

Despite the challenges of learning computer programming R is becoming the software of choice for many. The benefits far outweigh the problems for many individuals. Personally, I am looking forward to continuing to develop skills in understanding this dynamic software.