Variables in R
In this tutorial, we will learn about variables in R. We will cover the basics of declaring and using variables, including naming conventions.
What are Variables
Variables in R are used to store data values that can be manipulated during program execution. R is a dynamically typed language, meaning the data type of a variable can change at runtime.
Naming Variables
When naming variables in R, follow these conventions:
- Variable names must start with a letter or a period (.) followed by a letter.
- Subsequent characters can include letters, digits, periods, and underscores.
- Variable names are case-sensitive.
- Avoid using reserved keywords as variable names.
- Use snake_case or camelCase naming conventions for readability.
Syntax
The syntax to declare variables in R is:
variable_name <- value
# or
variable_name = value
Example 1: Variable storing Integer Value
In R, variables storing integer values hold whole numbers and also negative of the whole numbers, without decimal points.
For example,
- Declare an integer variable named
num
. - Assign a value of 10 to the variable.
- Print the value of the variable.
R Program
# Declare and initialize an integer variable
num <- 10
# Print the value of the variable
cat('The value of num is:', num, '\n')
Output
The value of num is: 10
Example 2: Variable storing String Value
In R, variables storing string values hold sequences of characters enclosed in quotes, allowing manipulation and processing of textual data.
For example,
- Declare a string variable named
name
. - Assign the value 'John' to the variable.
- Print the value of the variable.
R Program
# Declare and initialize a string variable
name <- 'John'
# Print the value of the variable
cat('The value of name is:', name, '\n')
Output
The value of name is: John
Example 3: Variable storing Boolean Value
In R, variables storing boolean values hold logical values of TRUE or FALSE, useful for conditional statements, logical operations, and program control flow.
For example,
- Declare a boolean variable named
is_true
. - Assign the value
TRUE
to the variable. - Print the value of the variable.
R Program
# Declare and initialize a boolean variable
is_true <- TRUE
# Print the value of the variable
cat('The value of is_true is:', is_true, '\n')
Output
The value of is_true is: TRUE