# assign the value 1 to the variable x
x <- 1 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 =
y = 3# 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
z <- 1 + 1
# 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
w <- 5 * 2
w[1] 10
Working with variables
Let’s do some computations with our variables
# Define result to be the product of z and 7
result <- z * 7
result[1] 14
# update the value of z to be 4^2
z <- 4^2Question: 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:
value <- 1
computed_result <- value * 10 + 3^2
value <- value + 2
computed_result * 2 [1] 38
Variable names
Which of the following are valid R variable names?
min_height
max.height
_age
.mass
MaxLength
min-length
2widths
celsius2kelvinThe generally recommended variable name convention is: variable_name