In this module, we will learn about variables & data types. Specifically:
Let us use a simple case study to understand variables. Suppose you are computing the area of a circle whose radius is 3. In R, you can do this straight away as shown below:
3.14 * 3 * 3
## [1] 28.26
But you cannot reuse the radius or the area computed in any other analysis or computation. Let us see how variables can change the above scenario and help us in reusing values and computations.
A variable consists of 3 components:
We can store the value of the radius by creating a variable and assigning it the value. In this case, we create a variable called radius
and assign it the value 3
using the assignment operator <-
.
radius <- 3
radius
## [1] 3
Now that we have learnt to create variables, let us see how we can use them for other computations. For our case study, we will use the radius
variable to compute the area of a circle.
We will create two variables, radius
and pi
, and use them to compute the area of a circle and store it in another variable area
.
# assign value 3 to variable radius
radius <- 3
# assign value 3.14 to variable pi
pi <- 3.14
# compute area of circle
area <- pi * radius * radius
# call radius
radius
## [1] 3
# call area
area
## [1] 28.26