# assign the value 1 to the variable x
<- 1 x
Introduction to R objects
In this document, we will learn how to define “objects” in R.
Defining objects
Let’s assign the value 1 to an object called x
We can view the value of x
by writing it’s name in a code chunk:
# view x
x
[1] 1
Another way to assign a value to a variable is using “=”
# assign the value of 3 to the variable y using =
= 3 y
# view y
y
[1] 3
You can also assign the output of mathematical calculations to a variable
# assign the output of 1 + 1 to the variable z
<- 1 + 1
z # view z
z
[1] 2
Exercise
As an exercise, your task is to define a new object w
that contains the output of the product of 5 and 2.
Create a new code chunk
Define the variable
w
, assign to it the output of the product of 5 and 2View the output of the object in the console.
Solution to exercise
<- 5 * 2
w w
[1] 10
Working with variables
Let’s do some computations with our variables
# Define result to be the product of z and 7
<- z * 7
result result
[1] 14
# update the value of z to be 4^2
<- 4^2 z
Question: Do you think result
will have changed?
Look at the values of result
and z
:
result
[1] 14
z
[1] 16
Exercise
What will the output of the following code chunk be:
<- 1
value <- value * 10 + 3^2
computed_result <- value + 2
value * 2 computed_result
[1] 38
Variable names
Which of the following are valid R variable names?
min_height
max.height
_age
.mass
MaxLength-length
min2widths
celsius2kelvin
The generally recommended variable name convention is: variable_name