3.14 * 3 * 3[1] 28.26
Practise this interactively in Course 1 (Introduction to R), lesson 2
Learning Objectives: After this chapter you will be able to:
- Explain what a variable is and why programs use them.
- Create and reassign variables with
<-.- Use variables in arithmetic and in function calls.
- Name variables legally, including the rule that permits a leading
..- Choose
snake_caseover periods, which are legal but discouraged.
In the previous chapter, we learned to install RStudio. In this chapter, we will learn about variables. You can skip this chapter if you have prior experience in another programming language.
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:
Every new analysis or computation would need the radius and the area typed again. Let us see how variables help us reuse values and computations.
A variable consists of 3 components:
We can store the radius by assigning its value to a variable. In this case, we create a variable called radius and assign it the value 3 using the assignment operator <-.
Now that we have learned 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 use radius and R’s built-in constant pi to compute the area of a circle and store it in another variable area. R already provides pi; there is no need to assign it a value.
.); e.g. .hidden <- 42 is valid in base R. Do not use numbers, dollar sign ($) or underscore (_) as the first character.-). Periods (.) are syntactically valid in R variable names, but are discouraged in modern style guides (tidyverse style prefers snake_case).average and Average would be different variables.<- to assign a value to a variable and the variable name to reuse it.pi.snake_case.Next: Data Types in R
Practise interactively: Course 1, lesson 2