Variables in R

Variables are used to organize and store data in R programming. The assignment operator (- or =) is used to assign values to variables. Here are some essential ideas regarding variables in R:

Names of variables:

  • MyVariable and myvariable are separate variables in R because of the case-sensitivity of variable names.
  • Letters, digits, or underscores must come before a dot (.) or a letter to begin a variable name.If it starts with period(.), it cannot be followed by a digit.
  • Choosing variable names that are descriptive and express the meaning of the data they contain is a smart practice.
  • Reserved words cannot be used as variables (TRUE, FALSE, NULL, if…)
  • A variable name cannot start with a number or underscore (_)

# Legal variable names:

myvar <- “technoexcel”

my_var <- “technoexcel””

myVar <- “technoexcel””

MYVAR <- “technoexcel””

myvar2 <- “technoexcel””

.myvar <- “technoexcel””

# Illegal variable names:

2myvar <- “technoexcel””

my-var <- “technoexcel””

my var <- “technoexcel””

_my_var <- “technoexcel””

my_v@ar <- “technoexcel”

TRUE <- “technoexcel”

Assignment:

  • You can assign values to variables using the <- operator or the = operator. For example:

x <- 10

y = “Hello, World!”

Data Types:

  • R is a dynamically-typed language, which means that variables can change their data type as you assign different values to them.
  • Common data types in R include numeric (e.g., integers or floating-point numbers), character (e.g., strings), logical (e.g., TRUE or FALSE), and more complex types like lists, data frames, and factors.

Checking Variable Types:

  • You can check the data type of a variable using the class() function. For example:

class(x)   # Returns “numeric”

class(y)   # Returns “character”

Vectors:

  • R is particularly well-suited for working with vectors (arrays) of data. You can create vectors and assign them to variables. For example:

numbers <- c(1, 2, 3, 4, 5)

Global vs. Local Scope:

  • Variables can have either global or local scope.
  • Global variables are accessible throughout your R session.
  • Local variables are defined within a function and are only accessible within that function’s scope.

Removing Variables:

  • You can remove a variable using the rm() function. For example:

rm(x)  # Removes the variable x

Constants:

  • While R doesn’t have built-in support for constants, it’s a convention to use uppercase variable names to indicate that a variable should not be modified as if it were a constant.

Here are some additional examples of variable usage in R:

# Creating variables

age <- 30

name <- “John Doe”

is_student <- TRUE

# Mathematical operations with variables

x <- 5

y <- 3

sum_result <- x + y

In summary, variables in R are used to store and manipulate data, and they play a central role in programming with the language.

Leave a Comment

Your email address will not be published. Required fields are marked *