O'Reilly logo

Learning R by Richard Cotton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. A Scientific Calculator

R is at heart a supercharged scientific calculator, so it has a fairly comprehensive set of mathematical capabilities built in. This chapter will take you through the arithmetic operators, common mathematical functions, and relational operators, and show you how to assign a value to a variable.

Chapter Goals

After reading this chapter, you should:

  • Be able to use R as a scientific calculator
  • Be able to assign a variable and view its value
  • Be able to use infinite and missing values
  • Understand what logical vectors are and how to manipulate them

Mathematical Operations and Vectors

The + operator performs addition, but it has a special trick: as well as adding two numbers together, you can use it to add two vectors. A vector is an ordered set of values. Vectors are tremendously important in statistics, since you will usually want to analyze a whole dataset rather than just one piece of data.

The colon operator, :, which you have seen already, creates a sequence from one number to the next, and the c function concatenates values, in this case to create vectors (concatenate is a Latin word meaning “connect together in a chain”).

Variable names are case sensitive in R, so we need to be a bit careful in this next example. The C function does something completely different to c:[6]

1:5 + 6:10         #look, no loops!
## [1]  7  9 11 13 15
c(1, 3, 6, 10, 15) + c(0, 1, 3, 6, 10)
## [1]  1  4  9 16 25

Tip

The colon operator and the c function are used almost everywhere in R code, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required