3 Making new data values
This chapter covers
- Performing operations between two or more data values
- Comparing values of the same or different type
- How R changes the data type as it needs to
You have your data values, but there’s a good chance you’ll want to do something with them, like add or multiply. It’s time to go back to basics and see how R deals with combining data. Thankfully, R is a readable language for things like this, and with any luck you’ll be able to code up what you’re trying to do with the operators you expect. Follow along with this chapter in the Console and try some values yourself to see if you get the results you expect.
3.1 Basic mathematics
The simplest thing you might want to do to two values is add them. No surprises here, the +
symbol (operator) between two values will do just that, the same as you would on a calculator:
2 + 2 #> [1] 4
The same goes for subtraction:
4 - 3 #> [1] 1
Multiplication in programming tends to use the asterisk (*
) rather than a multiply sign (technically, ×, but commonly seen as an x
):
3 * 6 #> [1] 18
Division uses a slash (/
) like you might use in writing a fraction:
12 / 4 #> [1] 3
One that might not be so obvious is the exponentiation operator, which raises a number to a power. This one is used, for example, when you need to square a value. There are two options, though in reality they’re different ways of writing the same thing. Here’s the first:
2 ^ 10 #> [1] 1024