6.3 Assigning data to an object

We will use an assignment operator to assign (i.e. store) data to an object:

You can use either <- or = (essentially the same).

Examples:

  • Assigning/storing 10 to the object named B:

Copy-paste the following in the console, and hit Enter.

B <- 10

This time, not there is no output. If you now type B in the R console, and hit Enter, what happens?

  • Reassigning: modifying the content of an object:
B <- 12
  • You can also use an object to assign data to a new (or to the same) object: try the following in the console:
B <- 12
A <- 5
A <- A + B

What values do A and B store now?

  • You can see the objects you created in the upper-right panel in RStudio that is, the environment:

R object env

How to name an object?

Naming an object in R is quite flexible.

You can use:

  • letters (note that object names case sensitive: A and a are NOT the same)
  • numbers (although the object name cannot start with a number)
  • underscores _

What you CANNOT use:

  • Spaces
  • Most special characters