R Variables, Constants and Reserved Words

R Variables

Variables are very similar to an open box, where you can put any value of your wish. We can change the values as well. Variables are used to store data.

A variable in R is used to store an atomic vector, group of atomic vectors or a combination of many R-objects.

  • A valid variable name can be a combination of numbers, letters, and the dot or underline character.
  • A valid variable name must start with a letter or a dot and if it starts with a dot, it cannot be followed by a number.
  • Reserved words in R cannot be used as a variable name. 

Variable Name

Validity

total

Valid

Sum

Valid

.this.is.ok

Valid

this _is_acceptable

Valid

tot@l

Invalid

var_name%

Invalid

_var_name

Invalid

5um

Invalid

TRUE

Invalid

We can separate the variables by the types of values they contain:

Boolean Variables: This is the simplest type of variable. It contains a single bit, and indicate a binary result (0 and 1, yes and no, or true and false).

Examples of Boolean variables are:

a = TRUE
b = FALSE

Integer variables: Numbers with no floating point are called integers. In R programming, sometimes it is difficult to declare a single integer. In most cases, try to do so will actually declare a numeric value.

Numeric Variables: Numeric variables are used to store numbers. It can contain floating point numbers.

Examples of Numeric variables are:

a = 1
b = 3.14

Characters Variables:  Character variables are used to store non-numeric data. Unlike other programming languages, there are a no differences between characters and strings in R.  Characters are assigned using quotation mark. R does not care if you use double or single quotes. Examples are:

a = “x”
c = “6”

String Variables:  String variables are those variables which contain one or more characters.  Examples are:

a = “abcd2”
b = “Hello World”

How to Create, Rename and Recode variables in R

In R, it is simple task to create a new variable or to convert an old variable into a new one.

Let's understand these all operations of variable through the given example:

First of all create a data set:

> hospital <- c("India", "US")
> patients <- c(200, 250)
> costs <- c(1000, 2000)
> df <- data.frame(hospital, patients, costs)
> df

Here, the name of dataset is df. When you run the above command, the output will be:

      hospital patients costs
1    India      200  1000
2       US      250  2000

Now we will create a new variable called totalcost as shown below:

> df$totalcost <- df$patients * df$costs
> df

Let's see the dataset again:

  hospital patients costs totalcost
1    India      200   2.5       500
2       US      250   3.1       775

Now, if we want to rename and recode a variable “costs” to “costs_rs” then:

> df$costs_rs <- df$costs
> df

Now the data set is:

  hospital patients costs totalcost costs_rs
1    India      200   2.5       500      2.5
2       US      250   3.1       775      3.1

We can also delete the variable through the NULL command, if we want to delete the costs variable then:

> df$totcosts <- NULL
> df

Then the dataset will be changed:

  hospital patients totalcost costs_rs
1    India      200       500      2.5
2       US      250       775      3.1

Now, let’s see that how to recode a variable “patients”. Here we use ifelse(), but you can use other functions as well:

df$patients <- ifelse(df$patients==200, 100, ifelse(df$patients==250, 300, NA))

Let's see the dataset again:

     hospital patients totalcost costs_rs
1    India      100       500      2.5
2       US      300       775      3.1

R Constants

Constants are the entities whose value cannot be changed. Basically there are two types of constants:

2. Numeric Constants: numeric constants are the numbers which can be integer, double or complex. You can check the type of constant through the typeof() function. Numeric constant suffix with L are the integer type and suffix with i are called complex type.

Example:

> typeof(10)
[1] "double"
> typeof(10L)
[1] "integer"
> typeof(10i)
[1] "complex"

2. Character Constant: Character constant can be declared using either single quote (‘ ’) or double quote (“ ”).

> typeof(“nikita”)
[1] “character”
> typeof(‘hello’)
[1] “character”

Built-in Constants: Some of the built-in constants of R along with their values are shown below:

> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T"
[21] "U" "V" "W" "X" "Y" "Z"
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t"
[21] "u" "v" "w" "x" "y" "z"
> month.name
[1] "January"   "February"  "March"     "April"     "May"       "June"     
[7] "July"      "August"    "September" "October"   "November"  "December"
> month.abb
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
> pi
[1] 3.141593

R Reserved Words

The set of words that have special meaning and cannot be used as an identifier (variable name, function name, etc.) are called Reserved words.

Following is the list of reserved words in R:

Reserved Words

Purpose

else

Conditional statements

repeat

Loop

While

Loop

function

User defined function

for

Loop

in

Loop

break

Loop

If

Conditional statements

TRUE

Logical constant

FALSE

Logical constant

NULL

Represents the absence of a value or an undefined value

Inf

Infinity

NaN

“Not a number”, e.g. when 0 is dived by 0

NA

Not Available

This list of reserved words can be viewed by the command help (reserved) or ?reserved.

> ?reserved
Note: Since R is a case sensitive language therefore TRUE and True are not the same. Here, TRUE is a reserved word and True can be a variable name. Reference: https://www.datamentor.io/r-programming/variable-constant/ https://intellipaat.com/tutorial/r-programming/basic-syntax-data-types-and-variables/

Related Topics

Bubble Chart in R Programming

In this article, we will talk about another type of chart in R programming, i.e., the Bubble chart. A bubble chart is a type of data visualization chart that helps display multiple...

4 minutes read.

R Tutorial

Introduction to R Programming R is nothing but a programming language, also a free software environment. This software used for predictive analysis, statistical analysis, graphical representation, data modeling, and reporting. R...

9 minutes read.

R JSON File

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. JSON file is often used when data is sent from a server to a...

2 minutes read.

R Line Graphs

Line graph or line chart is a graph that connects a series of points by drawing segments between them. A line graph represents the relationship between 2 variables. These points...

2 minutes read.

R Pie Charts

R programming language provides many numbers of libraries to create charts and graphs. A pie-chart is a representation of data as slices of a circle with different colors representing counts...

2 minutes read.

R Variables, Constants and Reserved Words

R Variables Variables are very similar to an open box, where you can put any value of your wish. We can change the values as well. Variables are used to store...

4 minutes read.

Introduction to R Programming

What is R Programming? R is a programming language which provides an environment for software used for statistical analysis, graphics representation and reporting. It possesses an extensive catalog of...

4 minutes read.

Various types of Charts in R Programming

As we know, R Language is mostly used for analyzing the data and statistics purposes to represent our data graphically & pictorially in R studio. Charts and graphs are plotted in...

4 minutes read.

Poisson Distribution in R Programming

Poisson distribution is a type of distribution that deals with the probability distribution of the data values by taking the mean into consideration. Poisson distribution will estimate the probability value for...

3 minutes read.

Binomial Distribution in R Programming

In this article, we will talk about the Binomial distribution in R programming. The binomial distribution is a type of probability distribution. As it is a discrete distribution, it will...

3 minutes read.

R Switch Statement

It is an alternate way to a nested if…else statement. A switch statement permits an expression to be tested against a list of case values. In short, we can say...

1 minute read.

R Operators

A symbol that tells the compiler to perform specific mathematical or logical operations is called operator. R language supports mainly 5 different types of operators, which are listed below: Arithmetic...

3 minutes read.

R If Else Statement

If statement It is the most simple decision-making statement. It checks the condition if the condition is true then only it will execute the block of statements written in the ‘if...

2 minutes read.

Decision Tree in R Programming

The decision tree uses the branching method to show every possible output for the specific input. We can draw a decision tree by hand or create it using specialized software...

2 minutes read.

Normal Distribution in R Programming

In statistics, the normal distribution is a type of probability function. Normal distribution tells the user about the distribution of data values in the dataset. It is a very important...

3 minutes read.

Measures of Central Tendency in R Programming

Central Tendency or CT is one of the features of descriptive statistics. The Central tendency will let us know how the various groups of data are clustered around the central...

4 minutes read.

First R Program

First  Hello World R Program As a convention, our first R program will be the “Hello World!” program. We can run our R program either at R command prompt or we...

3 minutes read.

Analysis of Covariance in R Programming

Analysis of Covariance can also be named ANCOVA. We know that we use the concept of regression analysis for creating models which can explain the effect of the variation in...

2 minutes read.

Clustering in R Programming

The clustering technique is an unsupervised machine learning in R programming. Before discussing clustering techniques, let's have a look at what unsupervised machine learning is?  Unsupervised learning is training the model with...

3 minutes read.

R Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.