0% found this document useful (0 votes)
7 views83 pages

R Data Types Explained: Numeric to Raw

Uploaded by

aruna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views83 pages

R Data Types Explained: Numeric to Raw

Uploaded by

aruna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Numeric Data type in R


Decimal values are called numeric in R. It is the default R data type for numbers in
R. If we assign a decimal value to a variable x as follows, x will be of numeric type.
Real numbers with a decimal point are represented using this data type in R. It
uses a format for double-precision floating-point numbers to represent numerical
values.
x = 5.6

print(class(x))

print(typeof(x))

Output

[1] "numeric"
[1] "double"
Even if an integer is assigned to a variable y, it is still saved as a numeric value.
y = 5

print(class(y))

print(typeof(y))

Output

[1] "numeric"
[1] "double"
When R stores a number in a variable, it converts the number into a "double" value
or a decimal type with at least two decimal places.
This means that a value such as "5" here, is stored as 5.00 with a type of double
and a class of numeric. And also y is not an integer here can be confirmed with
the [Link]() function.
y = 5

print([Link](y))

Output

[1] FALSE
2. Integer Data type in R
R supports integer data types which are the set of all integers. we can create as
well as convert a value into an integer type using the [Link]() function.
we can also use the capital 'L' notation as a suffix to denote that a particular value
is of the integer R data type.
x = [Link](5)

print(class(x))

print(typeof(x))

y = 5L

print(class(y))

print(typeof(y))

Output

[1] "integer"
[1] "integer"
[1] "integer"
[1] "integer"
3. Logical Data type in R
R has logical data types that take either a value of true or false. A logical value is
often created via a comparison between variables.
Boolean values, which have two possible values, are represented by this R data
type: FALSE or TRUE
x = 4
y = 3

z = x > y

print(z)

print(class(z))

print(typeof(z))

Output

[1] TRUE
[1] "logical"
[1] "logical"
4. Complex Data type in R
R supports complex data types that are set of all the complex numbers. The
complex data type is to store numbers with an imaginary component.
x = 4 + 3i

print(class(x))

print(typeof(x))

Output

[1] "complex"
[1] "complex"
5. Character Data type in R
R supports character data types where we have all the alphabets and special
characters. It stores character values or strings. Strings in R can contain
alphabets, numbers, and symbols.
The easiest way to denote that a value is of character type in R data type is to
wrap the value inside single or double inverted commas.
char = "Geeksforgeeks"

print(class(char))

print(typeof(char))

Output

[1] "character"
[1] "character"
There are several tasks that can be done using R data types. Let's understand
each task with its action and the syntax for doing the task along with an R code to
illustrate the task.
6. Raw data type in R
To save and work with data at the byte level in R, use the raw data type. By
displaying a series of unprocessed bytes, it enables low-level operations on binary
data. Here are some speculative data on R's raw data types:
x <- [Link](c(0x1, 0x2, 0x3, 0x4, 0x5))
print(x)

Output

[1] 01 02 03 04 05
Five elements make up this raw vector x, each of which represents a raw byte
value.
Find Data Type of an Object in R
To find the data type of an object we have to use class() function. The syntax for
doing that is we need to pass the object as an argument to the function class() to
find the data type of an object.
Syntax
class(object)
Example
print(class(TRUE))

print(class(3L))

print(class(10.5))

print(class(1+2i))

print(class("12-04-2020"))

Output

[1] "logical"
[1] "integer"
[1] "numeric"
[1] "complex"
[1] "character"

Type verification
We can verify the data type of an object, if we doubt about it's data type. To do
that, we need to use the prefix "is." before the data type as a command.
Syntax
is.data_type(object)
Example
print([Link](TRUE))

print([Link](3L))

print([Link](10.5))

print([Link](1+2i))

print([Link]("12-04-2020"))

print([Link]("a"))

print([Link](2+3i))

Output
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE

1. Creation of String in R
R Strings can be created by assigning character values to a variable. These strings
can be further concatenated by using various functions and methods to form a big
string.
str1 <- "OK1"
cat ("String 1 is : ", str1)

str2 <- 'OK2'


cat ("String 2 is : ", str2)

str3 <- "This is 'acceptable and 'allowed' in R"


cat ("String 3 is : ", str3)

str4 <- 'Hi, Wondering "if this "works"'


cat ("String 4 is : ", str4)

str5 <- 'hi, ' this is not allowed'


cat ("String 5 is : ", str5)
Output
String 1 is: OK1
String 2 is: OK2
String 3 is: This is 'acceptable and 'allowed' in R
String 4 is: Hi, Wondering "if this "works"
Error: unexpected symbol in " str5 <- 'hi, ' this"
Execution halted
2. Length of String
The length of strings indicates the number of characters present in the string.
2.1 Using the str_length() function
The function str_length() belonging to the 'string' package. It can be used to
determine the length of strings.
library(stringr)

str_length("hello")
Output
5
2.2 Using nchar() function
nchar() is a inbuilt function of R and can be used to determine the length of strings
in R.
nchar("hel'lo")
Output
6
3. Accessing portions of an R string
The individual characters of a string can be extracted from a string by using the
indexing methods of a string. There are two R's inbuilt functions in order to access
both the single character as well as the substrings of the string.
substr() or substring() function in R extracts substrings out of a string beginning
with the start index and ending with the end index. It also replaces the specified
substring with a new set of characters.
Syntax
substr(..., start, end)
#OR
substring(..., start, end)
3.1. Using substr() function
If the starting index is equal to the ending index, the corresponding character of the
string is accessed.
substr("Learn Code Tech", 1, 1)
Output
"L"
3.2. Using substring() function
Here, the number of characters in the string is 10. The first print statement prints
the last character of the string, "e", which is str[10]. The second print statement
prints the 11th character of the string, which doesn't exist, but the code doesn't
throw an error and print "", that is an empty character.
str <- "Learn Code"
len <- nchar(str)

print (substring(str, len, len))

print (substring(str, len+1, len+1))


Output
[1] "e"
The following R code indicates the mechanism of String Slicing, where in the
substrings of a R string are extracted:
str <- "Learn Code"

len <- nchar(str)


print(substr(str, 1, 4))
print(substr(str, len-2, len))
Output
[1]"Lear"
[1]"ode"
The first print statement prints the first four characters of the string. The second
print statement prints the substring from the indexes 8 to 10, which is "ode".
4. Case Conversion
The R string characters can be converted to upper or lower case by R's inbuilt
function
 toupper() converts all the characters to upper case
 tolower() converts all the characters to lower case
 casefold(..., upper=TRUE/FALSE) converts on the basis of the value specified
to the upper argument.
All these functions can take in as arguments multiple strings too. The time
complexity of all the operations is O(number of characters in the string).
str <- "Hi LeArn CodiNG"
print(toupper(str))
print(tolower(str))
print(casefold(str, upper = TRUE))
Output
[1] "HI LEARN CODING"
[1] "hi learn coding"
[1] "HI LEARN CODING"
By default, the value of upper in casefold() function is set to FALSE. If we set it to
TRUE, the R string gets printed in upper case.
5. Concatenation of R Strings
We can concatenate strings using paste() function.
In this example, we first create two strings "Hello" and "World" and store them in
the variables string1 and string2, respectively. We then use the paste() function
to concatenate the two strings together with a space between them and store the
result in the variable result. Finally, we use the print function to print the value
of result to the console.
string1 <- "Hello"
string2 <- "World"

result <- paste(string1, string2)

print(result)
Output
"Hello World"
We can see the output is Hello World, which is the concatenated string of "Hello"
and "World" with a space between them.
5.1. Concatenation of Multiple Strings
We can also concatenate multiple strings by passing them as separate arguments
to the paste function.
In this example, we concatenate three strings "Hello", "to", and "the World" and
store the result in the variable result. The paste function combines the strings
together with a space between them, so the output would be Hello to the World.
result <- paste("Hello", "to", "the World")

print(result)
Output
[1] "Hello to the World"
6. String formatting
String formatting in R is performed using the sprintf function.
In this example, we format a string with two decimal places using the %d format
specifier for the integer value x and the %.2f format specifier for the floating-point
value y. The prepared string is saved in the variable result before being written to
the console using the print function. The solution is 42, and pi is 3.14, which is the
formatted string with x and y values substituted for the format specifiers.
x <- 42
y <- 3.14159

result <- sprintf("The answer is %d, and pi is %.2f.", x, y)

print(result)
Output
[1] "John is 35 years old and 1.80 meters tall."
7. Updating the Strings
The characters, as well as substrings of a string, can be manipulated to new
string values. The changes are reflected in the original string.
Syntax:
substr (..., start, end) <- newstring
substring (..., start, end) <- newstring
Multiple strings can be updated at once, with the start <= end. But:
 If the length of the substring is larger than the new string, only the portion of the
substring equal to the length of the new string is replaced.
 If the length of the substring is smaller than the new string, the position of the
substring is replaced with the corresponding new string values.
string <- "Hello, World!"

string <- gsub("World", "Universe", string)

print(string)
Output
"Hello, Universe!"

Functions in R Programming
Last Updated : 12 Jul, 2025



A function accepts input arguments and produces the output by executing valid R
commands that are inside the function. Functions are useful when we want to
perform a certain task multiple times.
In R Programming Language when we are creating a function the function name and
the file in which we are creating the function need not be the same and we can have
one or more functions in R.
Creating a Function in R Programming
Functions are created in R by using the command function(). The general structure
of the function file is as follows:
Functions in R
Programming

Note: In the above syntax f is the function name, this means that we are creating a
function with name f which takes certain arguments and executes the following
statements.
Parameters or Arguments in R Functions
In programming, parameters and arguments refer to the values passed into a
function. They are often used interchangeably, but there is a subtle difference:
 Parameters are the variables defined in the function definition.
 Arguments are the actual values passed to the function when it is called.
A function can have multiple parameters, and these are separated by commas
within the parentheses.
Example:
add_num <- function(a,b)
{
sum_result <- a+b
return(sum_result)
}

sum = add_num(35,34)

print(sum)
Output
[1] 69
Function Parameter Rules
 Number of Parameters: A function should be called with the correct number of
parameters. If the number doesn't match, an error occurs.
 Default Parameter Values: Some functions have default values for parameters.
If no argument is passed, these defaults are used.
 Return Value: The return() function sends the result back from the function.
Read More: R Function Parameters
Calling a Function in R
After creating a Function, we have to call the function to use it. Calling a function in
R is done by writing it's name and passing possible parameters value.
Passing Arguments to Functions in R Programming Language
There are several ways we can pass the arguments to the function:
 Case 1: Generally in R, the arguments are passed to the function in the same
order as in the function definition.
 Case 2: If we do not want to follow any order what we can do is we can pass the
arguments using the names of the arguments in any order.
 Case 3: If the arguments are not passed the default values are used to execute
the function.
Now, let us see the examples for each of these cases in the following R code:
Rectangle = function(length=5, width=4){
area = length * width
return(area)
}

# Case 1:
print(Rectangle(2, 3))

# Case 2:
print(Rectangle(width = 8, length = 4))

# Case 3:
print(Rectangle())

Output

[1] 6
[1] 32
[1] 20

Types of Function in R Language


1. Built-in Function: Built-in functions in R are pre-defined functions that are
available in R programming languages to perform common tasks or operations.
2. User-defined Function: R language allow us to write our own function.
1. Built-in Function in R Programming Language
Built-in Function are the functions that are already existing in R language and we
just need to call them to use.
Here we will use built-in functions like sum(), max() and min().
print(sum(4:6))

print(max(4:6))

print(min(4:6))
Output
[1] 15
[1] 6
[1] 4
Other Built-in Functions in R
Let's look at the list of built-in R functions and their uses:
Category Function

Mathematical Functions abs(), sqrt(), round(), exp(), log(), cos(), sin(), tan()

Statistical Functions mean(), median(), cor(), var()

Data Manipulation Functions unique(), subset(), aggregate(), order()

File Input/Output Functions [Link](), [Link](), [Link](), [Link]()

2. User-defined Functions in R Programming Language


User-defined functions are the functions that are created by the user. The User
defines the working, parameters, default parameter, etc. of that user-defined
function. They can be only used in that specific code.
evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}

print(evenOdd(4))
print(evenOdd(3))
Output
[1] "even"
[1] "odd"
R Function Examples
Now let's look at some use cases of functions in R with some examples.
1. Single Input Single Output
Create a function that takes a single input and returns a single output. For example,
a function to calculate the area of a circle:
areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}
print(areaOfCircle(2))

Output

[1] 12.56637
2. Multiple Input Multiple Output
Create a function that takes multiple inputs and returns multiple outputs using a list.
For example, a function to calculate the area and perimeter of a rectangle:
Rectangle = function(length, width){
area = length * width
perimeter = 2 * (length + width)

result = list("Area" = area, "Perimeter" = perimeter)


return(result)
}

resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])

Output

$Area
[1] 6

$Perimeter
[1] 10
3. Inline Functions in R Programming Language
For small, quick functions, use inline functions. These are defined directly in the
expression.
f = function(x) x^2*4+x/3

print(f(4))
print(f(-2))
print(0)

Output

[1] 65.33333
[1] 15.33333
[1] 0

Lazy Evaluations of Functions in R Programming Language


In R, functions are executed lazily, meaning that if some arguments are missing, the
function still executes as long as those arguments are not involved in the execution.
For example, consider the following function Cylinder, which calculates the volume
of a cylinder using diameter and length. The argument radius is defined but not used
in the calculation.
Even if we don't pass the radius, the function will still execute because it doesn't
affect the volume calculation.
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
return(volume)
}

print(Cylinder(5, 10))

Output

[1] 196.3495
If we do not pass the argument and then use it in the definition of the function it will
throw an error that this "radius" is not passed and it is being used in the function
definition.
Example
Cylinder = function(diameter, length, radius ){
volume = pi*diameter^2*length/4
print(radius)
return(volume)
}

print(Cylinder(5, 10))
Output
Error in print(radius) : argument "radius" is missing, with no default
We have discussed all about R functions to give we some idea about using functions
in R language. we can go and study each individual in-built function on this page to
completely grasp the concept of R functions and their uses.
Loops in R (for, while, repeat)
Last Updated : 12 Jul, 2025



Loops are fundamental constructs in programming that allow repetitive execution of


code blocks. In R loops are primarily used for iterating over elements of a vector,
performing calculations and automating repetitive tasks. In this article we will learn
about different types of loops in R.
1. For Loop in R
The for loop is used when we know the exact number of iterations required. It
iterates over a sequence such as a vector, list or numeric range.
Syntax:
for (value in sequence)
{
statement
}
For Loop Flow Diagram:

Example 1: Program to display numbers from 1 to 5 using for loop.


Here, for loop is iterated over a sequence having numbers from 1 to 5. In each
iteration each item of the sequence is displayed.
for (val in 1: 5)
{
print(val)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Example 2: Program to display days of the week.
In this program initially all the days (strings) of the week are assigned to the vector
week. Then for loop is used to iterate over each string in a week. In each iteration,
each day of the week is displayed.
week <- c('Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday')

for (day in week)


{
print(day)
}
Output:
[1] "Sunday"
[1] "Monday"
[1] "Tuesday"
[1] "Wednesday"
[1] "Thursday"
[1] "Friday"
[1] "Saturday"
Example 3: For-Loop on a List
In this example we have a list of five numbers in this case. The seq_along() function
is used to create a list of indices to loop through and double brackets [[]] are used to
retrieve the current element during each loop iteration. We print a message showing
the element we're dealing with inside the loop followed by the value of that element.
my_list <- list(1, 2, 3, 4, 5)

for (i in seq_along(my_list)) {
current_element <- my_list[[i]]
print(paste("The current element is:", current_element))
}
Output
[1] "The current element is: 1"
[1] "The current element is: 2"
[1] "The current element is: 3"
[1] "The current element is: 4"
[1] "The current element is: 5"
Example 4: For-Loop on a Matrix
In this the integers in a 3x3 matrix range from 1 to 9. We cycle through the matrix's
rows and columns using two for-loops, each of which uses the [i, j] notation to
retrieve the current member. We output a message showing the element we're
dealing with inside the loop, followed by the value of that element.
my_matrix <- matrix(1:9, nrow = 3)

for (i in seq_len(nrow(my_matrix))) {
for (j in seq_len(ncol(my_matrix))) {
current_element <- my_matrix[i, j]
print(paste("The current element is:", current_element))
}
}
Output
[1] "The current element is: 1"
[1] "The current element is: 4"
[1] "The current element is: 7"
[1] "The current element is: 2"
[1] "The current element is: 5"
[1] "The current element is: 8"
[1] "The current element is: 3"
[1] "The current element is: 6"
[1] "The current element is: 9"
Example 5: For-Loop on a Data Frame
In this example we have a data frame with some sample information on the names,
ages and genders of persons. The data frame's rows are iterated using a for-loop
and each time the loop iterates, the current row is accessed using the [i] notation.
We print a message within the loop stating the row we are presently working with,
followed by the contents of that row.
my_dataframe <- [Link](
Name = c("Joy", "Juliya", "Boby", "Marry"),
Age = c(40, 25, 19, 55),
Gender = c("M", "F", "M", "F")
)

for (i in seq_len(nrow(my_dataframe))) {
current_row <- my_dataframe[i, ]
print(paste("The current row is:", toString(current_row)))
}
Output
[1] "The current row is: Joy, 40, M"
[1] "The current row is: Juliya, 25, F"
[1] "The current row is: Boby, 19, M"
[1] "The current row is: Marry, 55, F"
2. While Loop in R
The while loop runs as long as a specified condition holds TRUE. It is useful when
the number of iterations is unknown beforehand.
Syntax:
while ( condition )
{
statement
}
While loop Flow Diagram:

Example 1: Program to display numbers from 1 to 5 using a while loop in R.


In this example initially the variable value is initialized to 1. In each iteration of the
while loop the condition is checked and the value of val is displayed and then it is
incremented until it becomes 5 and the condition becomes false the loop is
terminated.
val = 1
while (val <= 5)
{
print(val)
val = val + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Example 2: Program to calculate the factorial of a number.
In this example at first the variable "n" is assigned to 5 whose factorial is going to be
calculated, then variable i and factorial are assigned to 1, i will be used for iterating
over the loop and factorial will be used for calculating the factorial. In each iteration
of the loop, the condition is checked i.e. i should be less than or equal to 5 and after
that factorial is multiplied with the value of i, then i is incremented. When i becomes
5 the loop is terminated and the factorial of 5 i.e. 120 is displayed beyond the scope
of the loop.
n <- 5
factorial <- 1
i <- 1

while (i <= n)
{
factorial = factorial * i
i = i + 1
}

print(factorial)
Output:
[1] 120
3. Repeat Loop in R
The repeat loop executes indefinitely until explicitly stopped using
the break statement. To terminate the repeat loop we use a jump statement that is
the break keyword.
Syntax:
repeat
{
statement

if( condition )
{
break
}
}
Repeat loop Flow Diagram:

Example 1: Display numbers from 1 to 5 using a repeat loop in R.


Here the variable val is initialized to 1, then in each iteration of the repeat loop the
value of val is displayed and then it is incremented until it becomes greater than 5. If
the value of val becomes greater than 5 then a break statement is used to terminate
the loop.
val = 1

repeat
{
print(val)
val = val + 1

if(val > 5)
{
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Example 2: Display a statement five times.
Here initially the variable i is initialized with 0 then in each iteration of the repeat loop
after printing "Geeks 4 geeks!" the value of i is incremented till it becomes 5 and the
condition in the if statement becomes true then the break statement is executed to
terminate the repeat loop.
i <- 0

repeat
{
print("Geeks 4 geeks!")
i = i + 1

if (i == 5)
{
break
}
}
Output:
[1] "Geeks 4 geeks!"
[1] "Geeks 4 geeks!"
[1] "Geeks 4 geeks!"
[1] "Geeks 4 geeks!"
[1] "Geeks 4 geeks!"
Example: if-else if-else ladder
# creating values
var1 <- 6
var2 <- 5

# checking if-else if ladder


if(var1 > 10 || var2 < 5){
print("condition1")
}else if(var1<7 && var2==5){
print("condition2")
}
Output
[1] "condition2"
Example: if-else if-else ladder
# creating values
var1 <- 6
var2 <- 5
var3 <- -4

# checking if-else if ladder


if(var1 > 10 || var2 < 5){
print("condition1")
}else if(var1<7 && var2==5 && var3>0){
print("condition2")
}else if(var1<7 && var2==5 && var3<0){
print("condition3")
}else{
print("condition4")
}
Output
[1] "condition3"
Creating Variables in R Language
R supports three ways of variable assignment:
 Using equal operator: operators use an arrow or an equal sign to assign
values to variables.
 Using the leftward operator: data is copied from right to left.
 Using the rightward operator: data is copied from left to right.
Syntax
Types of Variable Creation in R:
 Using equal to operators
variable_name = value

 using leftward operator


variable_name <- value

 using rightward operator


value -> variable_name
Example of Creating Variables in R
Let's look at the live example of creating Variables in R:
# using equal to operator
var1 = "hello"
print(var1)

# using leftward operator


var2 <- "hello"
print(var2)

# using rightward operator


"hello" -> var3
print(var3)

Output

[1] "hello"
[1] "hello"
[1] "hello"

Nomenclature of R Variables
When naming variables in R, it’s important to follow these rules:
1. Valid Characters: A variable name can include letters (a-z, A-Z), numbers (0-
9), dots (.), and underscores (_).
Example: var.1_ is valid.
2. No Special Characters: Only dots (.) and underscores (_) are allowed. Other
special characters like $ or # are not permitted.
Example: var$1 and var#1 are invalid.
3. Starting Characters: A variable name can start with a letter or a dot (.).
Example: .var and var are valid.
4. Cannot Start with Numbers or Underscore: A variable name cannot begin
with a number or an underscore.
Example: 2var and _var are invalid.
5. Dot Before Number: If a variable name starts with a dot (.), the character
following the dot cannot be a number.
Example: .3var is invalid.
6. Avoid Reserved Keywords: A variable name cannot be the same as a
reserved keyword in R, such as TRUE, FALSE, NA, etc.
Example: TRUE and FALSE are not allowed as variable names.
Important Methods for R Variables
R provides some useful methods to perform operations on variables. These
methods are used to determine the data type of the variable, finding a variable,
deleting a variable, etc. Following are some of the methods used to work on
variables:
1. class() function
This built-in function is used to determine the data type of the variable provided to
it. The R variable to be checked is passed to this as an argument and it prints the
data type in return.
Syntax
class(variable)
Example:
var1 = "hello"
print(class(var1))

Output

[1] "character"
2. ls() function
This built-in function is used to know all the present variables in the workspace.
This is generally helpful when dealing with a large number of variables at once and
helps prevents overwriting any of them.
Syntax:
ls()
Example:
# using equal to operator
var1 = "hello"

# using leftward operator


var2 <- "hello"

# using rightward operator


"hello" -> var3

print(ls())

Output

[1] "var1" "var2" "var3"


3. rm() function
This is again a built-in function used to delete an unwanted variable within your
workspace.
This helps clear the memory space allocated to certain variables that are not in use
thereby creating more space for others. The name of the variable to be deleted is
passed as an argument to it.
Syntax
rm(variable)
Example:
"hello" -> var3

# Removing variable
rm(var3)
print(var3)
Output:
Error in print(var3) : object 'var3' not found
Execution halted
Scope of Variables in R programming
The location where we can find a variable and also access it if required is called
the scope of a variable. There are mainly two types of variable scopes:
1. Global Variables
Global variables are those variables that exist throughout the execution of a
program. It can be changed and accessed from any part of the program.
As the name suggests, Global Variables can be accessed from any part of the
program.
 They are available throughout the lifetime of a program.
 They are declared anywhere in the program outside all of the functions or
blocks.
Global variables are usually declared outside of all of the functions and blocks.
They can be accessed from any portion of the program.
global = 5

# global variable accessed from within a function


display = function(){
print(global)
}
display()

# changing value of global variable


global = 10
display()

Output

[1] 5
[1] 10
In the above code, the variable 'global' is declared at the top of the program
outside all of the functions so it is a global variable and can be accessed or
updated from anywhere in the program.
2. Local Variables
Local variables are those variables that exist only within a certain part of a program
like a function and are released when the function call ends. Local variables do not
exist outside the block in which they are declared, i.e. they can not be accessed or
used outside that block.
Local variables are declared inside a block.
func = function(){
age = 18
print(age)
}

cat("Age is:\n")
func()

Output

Age is:
[1] 18

Difference Between Local and Global Variables in R


Aspect Global Variables Local Variables

Scope Defined outside any function and Defined within a function and
Aspect Global Variables Local Variables

accessible throughout the


accessible only within that function.
program.

Exists for the duration of the Exists only during the function's
Lifetime program’s execution or until execution, and is destroyed once
explicitly deleted. the function finishes.

Can cause naming conflicts if


Naming Restricted to the function where
used in multiple parts of the
Conflicts defined, reducing naming conflicts.
program.

Remains in memory throughout


Memory Created and destroyed when
the program, potentially using
Usage needed, using less memory.
more memory.

In this article, we’ve covered the basics of variables in R, how to create and use
them, and the differences between local and global variables

R-Vectors
Last Updated : 12 Jul, 2025



R Vectors are the same as the arrays in R language which are used to hold multiple
data values of the same type. One major key point is that in R Programming
Language the indexing of the vector will start from '1' and not from '0'. We can create
numeric vectors and character vectors as well.
R - Vector

1. Creating a vector in R
A vector is a basic data structure that represents a one-dimensional array. to create
a array we use the "c" function which the most common method use in R
Programming Language. We can also use seq() function or use colons ":" also as
shown in the example.
X<- c(61, 4, 21, 67, 89, 2)
cat('using c function', X, '\n')

Y<- seq(1, 10, [Link] = 5)


cat('using seq() function', Y, '\n')

Z<- 2:7
cat('using colon', Z)
Output:
using c function 61 4 21 67 89 2
using seq() function 1 3.25 5.5 7.75 10
using colon 2 3 4 5 6 7
2. Types of R vectors
Vectors are of different types which are used in R. Following are some of the types
of vectors:
2.1 Numeric vectors
Numeric vectors are those which contain numeric values such as integer, float,
etc. The L suffix in R is used to specify that a number is an integer and not a
numeric (floating-point) value.
v1 <- c(4, 5, 6, 7)
typeof(v1)

v2 <- c(1L, 4L, 2L, 5L)


typeof(v2)
Output:
[1] "double"
[1] "integer"
2.2 Character vectors
Character vectors in R contain alphanumeric values and special characters. In R,
when a vector contains elements of mixed types (like characters and numbers), R
automatically coerces the entire vector to a single type. Since characters are more
general than numbers in R, the vector is coerced to a character vector.
v1 <- c('geeks', '2', 'hello', 57)
typeof(v1)
Output:
[1] "character"
2.3 Logical vectors
Logical vectors in R contain Boolean values such as TRUE, FALSE and NA for Null
values. In R, NA is a special value used to represent missing or undefined data.
When used in a logical vector, NA is treated as a logical value because it is
specifically designed to work with logical vectors and other types of data.
v1 <- c(TRUE, FALSE, TRUE, NA)
typeof(v1)
Output:
[1] "logical"
3. Length of R vector
In R, the length of a vector is determined by the number of elements it contains. we
can use the length() function to retrieve the length of a vector.
x <- c(1, 2, 3, 4, 5)
length(x)

y <- c("apple", "banana", "cherry")


length(y)

z <- c(TRUE, FALSE, TRUE, TRUE)


length(z)
Output:
> length(x)
[1] 5

> length(y)
[1] 3

> length(z)
[1] 4
4. Accessing R vector elements
Accessing elements in a vector is the process of performing operation on an
individual element of a vector. There are many ways through which we can access
the elements of the vector. The most common is using the '[]', symbol.
Note: Vectors in R are 1 based indexing unlike the normal C, python, etc format.
X <- c(2, 5, 18, 1, 12)
cat('Using Subscript operator', X[2], '\n')

Y <- c(4, 8, 2, 1, 17)


cat('Using combine() function', Y[c(4, 1)], '\n')
Output:
Using Subscript operator 5
Using combine() function 1 4
5. Modifying a R vector
Modification of a Vector is the process of applying some operation on an individual
element of a vector to change its value in the vector. There are different ways
through which we can modify a vector:
X <- c(2, 7, 9, 7, 8, 2)

X[3] <- 1
X[2] <- 9
cat('subscript operator', X, '\n')

X[1:5] <- 0
cat('Logical indexing', X, '\n')

X <- X[c(3, 2, 1)]


cat('combine() function', X)
Output:
subscript operator 2 9 1 7 8 2
Logical indexing 0 0 0 0 0 2
combine() function 0 0 0
6. Deleting a R vector
Deletion of a Vector is the process of deleting all of the elements of the vector. This
can be done by assigning it to a NULL value.
M <- c(8, 10, 2, 5)

M <- NULL

print(cat('Output vector', M, "\f"))


Output:
Output vector NULL
7. Sorting elements of a R Vector
sort() function is used with the help of which we can sort the values in ascending or
descending order.
X <- c(8, 2, 7, 1, 11, 2)

A <- sort(X)
cat('ascending order', A, '\n')

B <- sort(X, decreasing = TRUE)


cat('descending order', B)
Output:
ascending order 1 2 2 7 8 11
descending order 11 8 7 2 2 1

R-Matrices
Last Updated : 12 Jul, 2025



R-matrix is a two-dimensional arrangement of data in rows and columns. In a


matrix, rows are the ones that run horizontally and columns are the ones that run
vertically. In R programming, matrices are two-dimensional, homogeneous data
structures. These are some examples of matrices:

R - Matrices

Creating a Matrix in R
To create a matrix in R you need to use the function called matrix().The arguments
to this matrix() are the set of elements in the vector. You have to pass how many
numbers of rows and how many numbers of columns you want to have in your
matrix.
Note: By default, matrices are in column-wise order.
Syntax
matrix(data, nrow, ncol, byrow, dimnames)
Parameters:
 data : values you want to enter
 nrow : no. of rows
 ncol : no. of columns
 byrow : logical clue, if 'true' value will be assigned by rows
 dimnames : names of rows and columns
Example:
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)

rownames(A) = c("a", "b", "c")


colnames(A) = c("c", "d", "e")

cat("The 3x3 matrix:\n")


print(A)

Output

The 3x3 matrix:


c d e
a 1 2 3
b 4 5 6
c 7 8 9

2. Creating Special Matrices in R


R allows the creation of various different types of matrices with the use of arguments
passed to the matrix() function.
2.1 Matrix where all rows and columns are filled by a single constant 'k'
To create such a R matrix the syntax is given below:
Syntax
matrix(k, m, n)
Parameters:
 k: the constant
 m: no of rows
 n: no of columns
Example:
print(matrix(5, 3, 3))

Output

[,1] [,2] [,3]


[1,] 5 5 5
[2,] 5 5 5
[3,] 5 5 5
2.2 Diagonal matrix
A diagonal matrix is a matrix in which the entries outside the main diagonal are all
zero. To create such a R matrix the syntax is given below:
Syntax
diag(k, m, n)
Parameters:
 k: the constants/array
 m: no of rows
 n: no of columns
Example:
print(diag(c(5, 3, 3), 3, 3))

Output

[,1] [,2] [,3]


[1,] 5 0 0
[2,] 0 3 0
[3,] 0 0 3
2.3 Identity matrix
An identity matrix in which all the elements of the principal diagonal are ones and all
other elements are zeros. To create such a R matrix the syntax is given below:
Syntax
diag(k, m, n)
Parameters:
 k: 1
 m: no of rows
 n: no of columns
Example:
print(diag(1, 3, 3))

Output

[,1] [,2] [,3]


[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
2.4. Matrix Metrics
Matrix metrics tell you about the Matrix you created. You might want to know the
number of rows, number of columns, dimensions of a Matrix.
Below Example will help you in answering following questions:
 How can you know the dimension of the matrix?
 How can you know how many rows are there in the matrix?
 How many columns are in the matrix?
 How many elements are there in the matrix?
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

cat("Dimension of the matrix:\n")


print(dim(A))

cat("Number of rows:\n")
print(nrow(A))

cat("Number of columns:\n")
print(ncol(A))

cat("Number of elements:\n")
print(length(A))
print(prod(dim(A)))

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Dimension of the matrix:
[1] 3 3
Number of rows:
[1] 3
Number of columns:
[1] 3
Number of elements:
[1] ...

3. Accessing Elements of a Matrix


We can access elements in the R matrices using the same convention that is
followed in data frames. So, we will have a matrix and followed by a square bracket
with a comma in between array. Value before the comma is used to access rows
and value that is after the comma is used to access columns.
3.1 Accessing rows
Let's see the example below on accessing specific rows in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

cat("Accessing first and second row\n")


print(A[1:2, ])

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Accessing first and second row
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
3.2 Accessing columns
Let's see the example below on accessing specific columns in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

cat("Accessing first and second column\n")


print(A[, 1:2])

Output
The 3x3 matrix:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Accessing first and second column
[,1] [,2]
[1,] 1 2
[2,] 4 5
[3,] 7 8
3.3 Accessing Elements of a matrix
Let's see the example below on accessing specific elements in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

print(A[1, 2]) # 1st row 2nd column

print(A[2, 3]) # 2nd row 3rd column

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[1] 2
[1] 6

4. Accessing Submatrices in R
We can access the submatrix in a matrix using the colon(:) operator.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

cat("Accessing the first three rows and the first two columns\n")
print(A[1:3, 1:2])

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Accessing the first three rows and the first two columns
[,1] [,2]
[1,] 1 2
[2,] 4 5
[3...

5. Modifying Elements of a Matrix


In R you can modify the elements of the matrices by a direct assignment.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

A[3, 3] = 30 # 3rd row 3rd column element is changed to 30

cat("After edited the matrix\n")


print(A)

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After edited the matrix
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 30

6. Matrix Concatenation
Matrix concatenation refers to the merging of rows or columns of an existing R
matrix.
6.1 Concatenation of a row
The concatenation of a row to a matrix is done using rbind().
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

B = matrix(
c(10, 11, 12),
nrow = 1,
ncol = 3
)
cat("The 1x3 matrix:\n")
print(B)

C = rbind(A, B)

cat("After concatenation of a row:\n")


print(C)

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
The 1x3 matrix:
[,1] [,2] [,3]
[1,] 10 11 12
After concatenation of a row:
[,1] [,2] [,3...
6.2 Concatenation of a column
The concatenation of a column to a matrix is done using cbind().
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

B = matrix(
c(10, 11, 12),
nrow = 3,
ncol = 1,
byrow = TRUE
)
cat("The 3x1 matrix:\n")
print(B)

C = cbind(A, B)

cat("After concatenation of a column:\n")


print(C)

Output

The 3x3 matrix:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
The 3x1 matrix:
[,1]
[1,] 10
[2,] 11
[3,] 12
After concatenation of a column:
[,1] [,2] ...
Dimension inconsistency: Note that you have to make sure the consistency of
dimensions between the matrix before you do this matrix concatenation.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

B = matrix(
c(10, 11, 12),
nrow = 1,
ncol = 3,
)
cat("The 1x3 matrix:\n")
print(B)

C = cbind(A, B)

cat("After concatenation of a column:\n")


print(C)
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
The 1x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 10 11 12

Error in cbind(A, B) : number of rows of matrices must match (see arg


2)
7. Adding Rows and Columns in a Matrix
To add a row in matrix you can use rbind() function and to add a column to matrix
you can use cbind() function.
7.1 Adding Row
Let's see below example on adding row in matrix
number <- matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before inserting a new row:\n")
print(number)
new_row <- c(10, 11, 12)

A <- rbind(number[1, ], new_row, number[-1, ])

cat("\nAfter inserting a new row:\n")


print(number)

Output

Before inserting a new row:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

After inserting a new row:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,]...
7.2 Adding Column
Let's see below example on adding column in matrix
number <- matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before adding a new column:\n")
print(number)

new_column <- c(10, 11, 12)

number <- cbind(number, new_column)

cat("\nAfter adding a new column:\n")


print(number)

Output

Before adding a new column:


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

After adding a new column:


new_column
[1,] 1 2 3 10
[2,] 4 5 6 1...

8. Deleting Rows and Columns of a Matrix


To delete a row or a column, first of all, you need to access that row or column and
then insert a negative sign before that row or column. It indicates that you had to
delete that row or column.
8.1 Row deletion
Let's see the example below on deleting a row in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before deleting the 2nd row\n")
print(A)

A = A[-2, ]

cat("After deleted the 2nd row\n")


print(A)

Output

Before deleting the 2nd row


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After deleted the 2nd row
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
8.2 Column deletion
Let's see the example below on deleting a column in a matrix.
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("Before deleting the 2nd column\n")
print(A)

A = A[, -2]

cat("After deleted the 2nd column\n")


print(A)

Output

Before deleting the 2nd column


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
After deleted the 2nd column
[,1] [,2]
[1,] 1 3
[2,] 4 6
[3,] 7 9
We have discussed the about matrices and their basic operations like adding new
rows and columns, deleting rows and columns, merging matrices ,etc.
Also Check:
 R - Array
 R - Lists
 R - Tuples
R Data Frames Structure
As we can see in the image below, this is how a data frame is structured. The data
is presented in tabular form, which makes it easier to operate and understand.

R - Data Frames

1. Create Data Frame in R Programming Language


To create an R data frame use [Link]() function and then pass each of the
vectors we have created as arguments to the function.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
print([Link])
Output:

R - Data Frames

2. Printing Structure of the R Data Frame


One can get the structure of the R data frame using str() function in R. It can
display even the internal structure of large lists which are nested. It provides one-
liner output for the basic R objects letting the user know about the object and its
constituents.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
print(str([Link]))
Output:

R - Data Frames

3. Summary of Data in the R data frame


In the R data frame, the statistical summary and nature of the data can be obtained
by applying summary() function. It is a generic function used to produce result
summaries of the results of various model fitting functions. The function invokes
particular methods which depend on the class of the first argument.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
print(summary([Link]))
Output:
R - Data Frames

4. Extract Data from Data Frame in R


Extracting data from an R data frame means that to access its rows or columns.
One can extract a specific column from an R data frame using its column name.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)

result <- [Link]([Link]$friend_name)


print(result)
Output:

R - Data Frames

5. Expand Data Frame in R


A data frame in R can be expanded by adding new columns and rows to the
already existing R data frame.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)

[Link]$location <- c("Kolkata", "Delhi",


"Bangalore", "Hyderabad",
"Chennai")
resultant <- [Link]
print(resultant)
Output:
R - Data Frames

In R, one can perform various types of operations on a data frame like accessing
rows and columns, selecting the subset of the data frame, editing data
frames, delete rows and columns in a data frame, etc.
Please refer to DataFrame Operations in R to know about all types of operations
that can be performed on a data frame.
6. Access Items in R Data Frame
We can select and access any element from data frame by using
single $ ,brackets [ ] or double brackets [[]] to access columns from a data
frame.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)

print([Link][1])

[Link][['friend_name']]

print([Link]$friend_id)
Output:

R - Data Frames

7. Amount of Rows and Columns in R Data Frame


We can find out how many rows and columns present in our data frame by using
dim function.
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)

dim([Link])
Output:
[1] 5 2
8. Add Rows and Columns
We can easily add rows and columns in a data frame. Insertion helps in expanding
the already existing data frame, without needing a new one.
8.1 Add Rows in R Data Frame
To add rows in a Data Frame, we can use a built-in function rbind(). Following
example demonstrate the working of rbind() in R Data Frame.
Products <- [Link](
Product_ID = c(101, 102, 103),
Product_Name = c("T-Shirt", "Jeans", "Shoes"),
Price = c(15.99, 29.99, 49.99),
Stock = c(50, 30, 25)
)

cat("Existing dataframe (Products):\n")


print(Products)

New_Product <- c(104, "Sunglasses", 39.99, 40)


Products <- rbind(Products, New_Product)

cat("\nUpdated dataframe after adding a new product:\n")


print(Products)
Output:

R - Data Frames

8.2 Add Columns in R Data Frame


To add columns in a Data Frame, we can use a built-in function cbind(). Following
example demonstrate the working of cbind() in R Data Frame.
Products <- [Link](
Product_ID = c(101, 102, 103),
Product_Name = c("T-Shirt", "Jeans", "Shoes"),
Price = c(15.99, 29.99, 49.99),
Stock = c(50, 30, 25)
)

cat("Existing dataframe (Products):\n")


print(Products)

Discount <- c(5, 10, 8)


Products <- cbind(Products, Discount)

colnames(Products)[ncol(Products)] <- "Discount"

cat("\nUpdated dataframe after adding a new column 'Discount':\n")


print(Products)
Output:

R - Data Frames

9. Remove Rows and Columns


A data frame in R removes columns and rows from the already existing R data
frame.
9.1 Remove Row in R Data Frame
We first created a data frame called data with three columns: friend_id,
friend_name, and location. To remove a row with friend_id equal to 3, we used the
subset() function and specified the condition friend_id != 3. This removed the row
with friend_id equal to 3.
library(dplyr)

data <- [Link](


friend_id = c(1, 2, 3, 4, 5),
friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"),
location = c("Kolkata", "Delhi", "Bangalore", "Hyderabad", "Chennai")
)

print(data)
data <- subset(data, friend_id != 3)

print(data)
Output:

R - Data Frames

9.2 Remove Column in R Data Frame


To remove the location column, we used the select() function and specified -
location. The - sign indicates that we want to remove the location column. The
resulting data frame data will have only two columns: friend_id and friend_name.
library(dplyr)

data <- [Link](


friend_id = c(1, 2, 3, 4, 5),
friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"),
location = c("Kolkata", "Delhi", "Bangalore", "Hyderabad", "Chennai")
)

print(data)

data <- select(data, -location)

print(data)
Output:

R - Data Frames
10. Combining Data Frames in R
There are 2 way to combine data frames in R. we can either combine them
vertically or horizontally. Let's look at both cases with example:
10.1 Combine Data Frame Vertically
If we want to combine 2 data frames vertically, we can use rbind() function. This
function works for combination of two or more data frames.
df1 <- [Link](
Name = c("Alice", "Bob"),
Age = c(25, 30),
Score = c(80, 75)
)

df2 <- [Link](


Name = c("Charlie", "David"),
Age = c(28, 35),
Score = c(90, 85)
)

cat("Dataframe 1:\n")
print(df1)

cat("\nDataframe 2:\n")
print(df2)

combined_df <- rbind(df1, df2)

cat("\nCombined Dataframe:\n")
print(combined_df)
Output:

R - Data Frames
10.2 Combine Data Frame Horizontally
If we want to combine 2 data frames horizontally, we can use cbind()
function. This function works for combination of two or more data frames.
df1 <- [Link](
Name = c("Alice", "Bob"),
Age = c(25, 30),
Score = c(80, 75)
)

df2 <- [Link](


Height = c(160, 175),
Weight = c(55, 70)
)

cat("Dataframe 1:\n")
print(df1)

cat("\nDataframe 2:\n")
print(df2)

combined_df <- cbind(df1, df2)

cat("\nCombined Dataframe:\n")
print(combined_df)
Output:

R - Data Frames
calculate the mean and standard deviation of a dataset:
 We first create a vector data that contains numerical values.
 We use the mean() function to calculate the mean of the dataset.
 The sd() function calculates the standard deviation.

data <- c(5, 10, 15, 20, 25, 30, 35, 40, 45, 50)

mean_data <- mean(data)


print(paste("Mean: ", mean_data))

std_dev <- sd(data)


print(paste("Standard Deviation: ", std_dev))

Output:
[1] "Mean: 27.5"
[1] "Standard Deviation: 15.1382517704875"

1. Creating a List
To create a List in R you need to use the function called "list()". We want to build a
list of employees with the details. So for this, we want attributes such as ID,
employee name, and the number of employees.
Example:

empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(empId, empName, numberOfEmp)

print(empList)

Output
[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"

[[3]]
[1] 4

2. Naming List Components


Naming list components make it easier to access them.
Example:
my_named_list <- list(name = "Sudheer", age = 25, city = "Delhi")

print(my_named_list)

Output
$name
[1] "Sudheer"

$age
[1] 25

$city
[1] "Delhi"

3. Accessing R List Components


We can access components of an R list in two ways.
3.1. Access components by names:
All the components of a list can be named and we can use those names to access
the components of the R list using the dollar command.
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
print(empList)
cat("Accessing name components using $ command\n")
print(empList$Names)

Output
$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"

$`Total Staff`
[1] 4

Accessing name components using $ command


[1] "Debi" "Sandeep" "Subham" "Shiba"

3.2. Access components by indices:


We can also access the components of the R list using indices. To access the top-
level components of a R list we have to use a double slicing operator "[[ ]]" which is
two square brackets and if we want to access the lower or inner-level components
of a R list we have to use another square bracket "[ ]" along with the double slicing
operator "[[ ]]".
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
print(empList)

cat("Accessing name components using indices\n")


print(empList[[2]])

cat("Accessing Sandeep from name using indices\n")


print(empList[[2]][2])

cat("Accessing 4 from ID using indices\n")


print(empList[[1]][4])
Output
$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"

$`Total Staff`
[1] 4

Accessing name components using indices


[1] "Debi" "Sandeep" "Subham" "Shiba"
Accessing Sandeep from na...

4. Modifying Components of a List


A R list can also be modified by accessing the components and replacing them
with the ones which you want.
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
cat("Before modifying the list\n")
print(empList)

empList$`Total Staff` = 5
empList[[1]][5] = 5
empList[[2]][5] = "Kamala"

cat("After modified the list\n")


print(empList)

Output
Before modifying the list
$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"

$`Total Staff`
[1] 4

After modified the list


$ID
[1] 1 2 3 4 5

$Names
[1] "Debi" "Sandeep" "Subham" ...

5. Concatenation of lists
Two R lists can be concatenated using the concatenation function. So, when we
want to concatenate two lists we have to use the concatenation operator.
Syntax
list = c(list, list1)
list = the original list
list1 = the new list
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
cat("Before concatenation of the new list\n")
print(empList)

empAge = c(34, 23, 18, 45)


empList = c(empName, empAge)

cat("After concatenation of the new list\n")


print(empList)

Output
Before concatenation of the new list
$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"

$`Total Staff`
[1] 4

After concatenation of the new list


[1] "Debi" "Sandeep" "Subham" "S...

6. Adding Item to List


To add an item to the end of list, we can use append() function.
my_numbers = c(1,5,6,3)

append(my_numbers, 45)

my_numbers

Output
[1] 1 5 6 3 45
[1] 1 5 6 3

7. Deleting Components of a List


To delete components of a R list, first of all, we need to access those components
and then insert a negative sign before those components. It indicates that we had
to delete that component.
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4

empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
cat("Before deletion the list is\n")
print(empList)

cat("After Deleting Total staff components\n")


print(empList[-3])

cat("After Deleting sandeep from name\n")


print(empList[[2]][-2])

Output
Before deletion the list is
$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"

$`Total Staff`
[1] 4

After Deleting Total staff components


$ID
[1] 1 2 3 4

$Names
[1] "Debi" "Sand...

8. Merging list
We can merge the R list by placing all the lists into a single list.
lst1 <- list(1,2,3)
lst2 <- list("Sun","Mon","Tue")

new_list <- c(lst1, lst2)

print(new_list)
Output:
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
9. Converting List to Vector
Here we are going to convert the R list to vector, for this we will create a list first
and then unlist the list into the vector.
lst <- list(1:5)
print(lst)

vec <- unlist(lst)

print(vec)

Output
[[1]]
[1] 1 2 3 4 5

[1] 1 2 3 4 5
Factors in R Programming Language are used to represent categorical data,
such as "male" or "female" for gender. While they might seem similar to character
vectors, factors are actually stored as integers with corresponding labels. Factors
are useful when dealing with data that has a fixed set of possible values, known
as levels. These levels are sorted alphabetically by default, and once created, a
factor can only contain those predefined levels.
Attributes of Factors in R Language
 x: The vector to be converted into a factor.
 Levels: The distinct values assigned to the factor.
 Labels: Character labels for each level.
 Exclude: Specifies values to exclude from the factor.
 Ordered: Indicates whether the factor levels should be ordered.
 nmax: Sets the maximum number of levels allowed for the factor.
1. Creating a Factor in R Programming Language
To create a factor in R, we use the factor() function, which converts a vector into
a factor. Here are the two main steps:
1. Create a vector: Start by defining a vector with the values you want to
categorize.
2. Convert the vector into a factor: Use the factor() function to turn the vector
into a factor, defining its levels.
Example: Creating a Gender Factor
Let’s create a factor for gender with the levels "female", "male", and "transgender".
x <-c("female", "male", "male", "female")
print(x)

gender <-factor(x)
print(gender)
Output
[1] "female" "male" "male" "female"
[1] female male male female
Levels: female male
Levels can also be predefined by the programmer.
gender <- factor(c("female", "male", "male", "female"),
levels = c("female", "transgender", "male"))

print(gender)
Output
[1] female male male female
Levels: female transgender male
Further one can check the levels of a factor by using function levels().
2. Checking for a Factor in R
The function [Link]() is used to check whether the variable is a factor and
returns "TRUE" if it is a factor.
gender <- factor(c("female", "male", "male", "female"));
print([Link](gender))
Output
[1] TRUE
Function class() is also used to check whether the variable is a factor and if true
returns "factor".
gender <- factor(c("female", "male", "male", "female"))
class(gender)
Output
[1] "factor"

3. Accessing elements of a Factor in R


We can access the elements of a factor. If gender is a factor then gender[i] would
mean accessing an ithith element in the factor.
gender <- factor(c("female", "male", "male", "female"))
print(gender[3])
Output
[1] male
Levels: female male
More than one element can be accessed at a time.
gender <- factor(c("female", "male", "male", "female"))
print(gender[c(2, 4)])
Output
[1] male female
Levels: female male

4. Modification of a Factor in R
After a factor is formed, its components can be modified but the new values which
need to be assigned must be at the predefined level.
Example
gender <- factor(c("female", "male", "male", "female" ))
gender[2]<-"female"
print(gender)
Output
[1] female female male female
Levels: female male

For selecting all the elements of the factor gender except ithith element, gender[-i]
should be used. So if you want to modify a factor and add value out of predefined
levels, then first modify levels.
gender <- factor(c("female", "male", "male", "female" ))

levels(gender) <- c(levels(gender), "other")


gender[3] <- "other"

print(gender)
Output
[1] female male other female
Levels: female male other

5. Removing Elements from a factor in R


Subtract one element at a time by using square brackets to subset the vector and
remove the element.
gender <- factor(c("female", "male", "male", "female" ))
print(gender[-3])
Output
[1] female male female
Levels: female male

6. Factors in Data Frame


A Data frame in R is similar to a 2D array, where each column represents a
variable and each row represents a set of values for those variables. When
working with data frames in R, we need to keep these points in mind:
 Column names are required and cannot be empty.
 Each row must have unique names.
 Data in a data frame can only be of three types: factor, numeric, or character.
 Each column must have the same number of data entries.
age <- c(40, 49, 48, 40, 67, 52, 53)

salary <- c(103200, 106200, 150200,


10606, 10390, 14070, 10220)

gender <- c("male", "male", "transgender",


"female", "male", "female", "transgender")

employee <- [Link](age, salary, gender = factor(gender))

print(employee)

print([Link](employee$gender))
Output
age salary gender
1 40 103200 male
2 49 106200 male
3 48 150200 transgender
4 40 10606 female
5 67 10390 male
6 52 14070 female
7 53 10220 transgender
[1] TRUE
In this article, we explored the concept of factors in R, how to create and modify
them, and how they are used in data frames to represent categorical data
efficiently.
Get Date and Time in different Formats in R
Programming - date(), [Link](), [Link]() and
[Link]() Function
Last Updated : 15 Jul, 2025



date()function in R Language is used to return the current date and time.


Syntax: date() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# date function

# Calling date() function to


# return current date and time
date()
Output:

[1] "Thu Jun 11 04:29:39 2020"


[Link]() Function
[Link]() function is used to return the system's date.

Syntax: [Link]() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the system's date
[Link]()
Output:

[1] "2020-06-11"
[Link]()
[Link]() function is used to return the system's date and time.

Syntax: [Link]() Parameters: Does not accept any parameters


Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the system's date and time
[Link]()
Output:

[1] "2020-06-11 05:35:49 UTC"


[Link]()
[Link]() function is used to return the current time zone.

Syntax: [Link]() Parameters: Does not accept any parameters

Example:
# R program to illustrate
# [Link] function

# Calling [Link]() function to


# return the current time zone
[Link]()
Output:

[1] "Etc/UTC"
Working with CSV files in R Programming
Last Updated : 17 May, 2025



CSV (Comma-Separated Values) files are plain text files where each row contains
data values separated by commas or other delimiters such as tabs. These files are
commonly used for storing tabular data and can be easily imported and manipulated
in R. We will explore how to efficiently work with CSV files in R Programming
Language. We will cover key functions for reading, querying, and writing CSV data,
along with practical examples and explanations.
Getting and Setting the Working Directory
Before working with CSV files, it is important to know and set the working directory
where your CSV files are stored.
print(getwd())

setwd("/Example_Path/")

print(getwd())
 getwd()retrieves the current working directory in R.
 setwd()changes the working directory to the specified path.
Example Output:
"C:/Users/GFG19565/Documents"
[1]"C:/Users/GFG19565/Documents"
1. Sample CSV File Example
Consider the following sample CSV data saved as [Link]:
id,name,department,salary,projects
1,A,IT,60754,4
2,B,Tech,59640,2
3,C,Marketing,69040,8
4,D,Marketing,65043,5
5,E,Tech,59943,2
6,F,IT,65000,5
7,G,HR,69000,7
We can create this file using any text editor (like notepad) and save it to your
working directory.
2. Reading CSV Files into R
We can load a CSV file into R as a data frame using the [Link]() function.
The ncol() and nrow() return the number of columns and rows in the data frame,
respectively.
csv_data <- [Link](file = 'C:\\Users\\GFG19565\\Downloads\\[Link]')
return(csv_data)

print(ncol(csv_data))
print(nrow(csv_data))
Output:

Printing the contents of csv file

3. Querying Data in CSV Files


We can perform queries on your CSV data using base R functions to filter and
summarize data.
1. Find minimum projects
Uses the min() function on the projects column to find the smallest value.
min_pro <- min(csv_data$projects)
print(min_pro)
Output:
[1] 2
2. Filter employees with salary greater than 60000 and select columns
Here we filter rows where salary exceeds 60000 and selects
only name and salary columns from filtered data.
result <- csv_data[csv_data$salary > 60000, c("name", "salary")]
print(result)
Output:

Query Result

Writing Data to CSV Files


We can write processed data back into a CSV file using [Link]().
1. Calculate average salary per department
The tapply() function applies the mean() function to salary grouped by department.
result <- tapply(csv_data$salary, csv_data$department, mean)

result_df <- [Link](Department = names(result), AverageSalary =


[Link](result))

[Link](result_df, "Mean_salary.csv", [Link] = FALSE)


Output:

Writing into csv


file

2. Calculate total number of projects handled per department and write to CSV
The tapply() function is used to compute the total number of projects handled in
each department. The result is converted into a data frame for better structure and
then written to a CSV file named department_project_totals.csv.
total_projects <- tapply(csv_data$projects, csv_data$department, sum)

projects_df <- [Link](Department = names(total_projects), TotalProjects =


total_projects)
[Link](projects_df, "department_project_totals.csv", [Link] = FALSE)
Output:
Working with Excel Files in R Programming
Last Updated : 12 Jul, 2025



Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start
working with excel files in R Programming Language, we need to first import excel
files in RStudio or any other R supporting IDE(Integrated development environment).
Reading Excel Files in R Programming Language
First, install readxl package in R to load excel files. Various methods including their
subparts are demonstrated further.
Sample_data1.xlsx:
Sample_data2.xlsx:
Reading Files:
The two excel files Sample_data1.xlsx and Sample_data2.xlsx and read from the
working directory.
# Working with Excel Files
# Installing required package
[Link]("readxl")

# Loading the package


library(readxl)

# Importing excel file


Data1 < - read_excel("Sample_data1.xlsx")
Data2 < - read_excel("Sample_data2.xlsx")

# Printing the data


head(Data1)
head(Data2)
The excel files are loaded into variables Data_1 and Data_2 as a dataframes and
then variable Data_1 and Data_2 is called that prints the dataset.
Modifying Files
The Sample_data1.xlsx file and Sample_file2.xlsx are modified.
# Modifying the files
Data1$Pclass <- 0

Data2$Embarked <- "S"

# Printing the data


head(Data1)
head(Data2)
The value of the P-class attribute or variable of Data1 data is modified to 0. The
value of Embarked attribute or variable of Data2 is modified to S.
Deleting Content from files
The variable or attribute is deleted from Data1 and Data2 datasets containing
Sample_data1.xlsx and Sample_data2.xlsx files.
# Deleting from files
Data1 <- Data1[-2]

Data2 <- Data2[-3]

# Printing the data


Data1
Data2

The - sign is used to delete columns or attributes from the dataset. Column 2 is
deleted from the Data1 dataset and Column 3 is deleted from the Data2 dataset.
Merging Files
The two excel datasets Data1 and Data2 are merged using merge() function which
is in base package and comes pre-installed in R.
# Merging Files
Data3 <- merge(Data1, Data2, all.x = TRUE, all.y = TRUE)

# Displaying the data


head(Data3)
Data1 and Data2 are merged with each other and the resultant file is stored in the
Data3 variable.
Creating new columns
New columns or features can be easily created in Data1 and Data2 datasets.
# Creating feature in Data1 dataset
Data1$Num < - 0

# Creating feature in Data2 dataset


Data2$Code < - "Mission"

# Printing the data


head(Data1)
head(Data2)

Num is a new feature that is created with 0 default value in Data1 dataset. Code is a
new feature that is created with the mission as a default string in Data2 dataset.
Writing Files
After performing all operations, Data1 and Data2 are written into new files
using [Link]() function built in writexl package.
# Installing the package
[Link]("writexl")

# Loading package
library(writexl)

# Writing Data1
write_xlsx(Data1, "New_Data1.xlsx")

# Writing Data2
write_xlsx(Data2, "New_Data2.xlsx")
The Data1 dataset is written New_Data1.xlsx file and Data2 dataset is written
in New_Data2.xlsx file. Both the files are saved in the present working directory.
# Function to convert Fahrenheit to Celsius

fahrenheit_to_celsius <- function(fahrenheit) {

return((fahrenheit - 32) * 5/9)

# Function to convert Celsius to Fahrenheit

celsius_to_fahrenheit <- function(celsius) {

return((celsius * 9/5) + 32)

# Main program loop

repeat {

# Display menu

cat("Temperature Conversion Menu:\n")

cat("1. Convert Fahrenheit to Celsius\n")


cat("2. Convert Celsius to Fahrenheit\n")

cat("3. Exit\n")

# Get user choice

choice <- [Link](readline(prompt = "Enter your choice (1, 2, or 3): "))

# Process choice

if (choice == 1) {

temp_f <- [Link](readline(prompt = "Enter temperature in Fahrenheit: "))

temp_c <- fahrenheit_to_celsius(temp_f)

cat(sprintf("%.2f Fahrenheit is equal to %.2f Celsius.\n", temp_f, temp_c))

} else if (choice == 2) {

temp_c <- [Link](readline(prompt = "Enter temperature in Celsius: "))

temp_f <- celsius_to_fahrenheit(temp_c)

cat(sprintf("%.2f Celsius is equal to %.2f Fahrenheit.\n", temp_c, temp_f))

} else if (choice == 3) {

cat("Exiting program.\n")

break # Exit the loop

} else {

cat("Invalid choice. Please enter 1, 2, or 3.\n")

cat("\n") # Add a newline for better readability

You might also like