R Data Types Explained: Numeric to Raw
R Data Types Explained: Numeric to Raw
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)
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(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
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!"
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
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()
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)
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
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
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:
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:
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
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"
print(ls())
Output
# 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
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
Scope Defined outside any function and Defined within a function and
Aspect Global Variables Local Variables
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.
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')
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)
> 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')
X[3] <- 1
X[2] <- 9
cat('subscript operator', X, '\n')
X[1:5] <- 0
cat('Logical indexing', X, '\n')
M <- NULL
A <- sort(X)
cat('ascending order', A, '\n')
R-Matrices
Last Updated : 12 Jul, 2025
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
)
Output
Output
Output
Output
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
Output
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)
Output
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
Output
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)
Output
B = matrix(
c(10, 11, 12),
nrow = 3,
ncol = 1,
byrow = TRUE
)
cat("The 3x1 matrix:\n")
print(B)
C = cbind(A, B)
Output
B = matrix(
c(10, 11, 12),
nrow = 1,
ncol = 3,
)
cat("The 1x3 matrix:\n")
print(B)
C = cbind(A, B)
Output
Output
A = A[-2, ]
Output
A = A[, -2]
Output
R - Data Frames
R - Data Frames
R - Data Frames
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
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)
)
R - Data Frames
R - Data Frames
print(data)
data <- subset(data, friend_id != 3)
print(data)
Output:
R - Data Frames
print(data)
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)
)
cat("Dataframe 1:\n")
print(df1)
cat("\nDataframe 2:\n")
print(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)
)
cat("Dataframe 1:\n")
print(df1)
cat("\nDataframe 2:\n")
print(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)
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
print(empList)
Output
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]]
[1] 4
print(my_named_list)
Output
$name
[1] "Sudheer"
$age
[1] 25
$city
[1] "Delhi"
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
empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
print(empList)
$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"
$`Total Staff`
[1] 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"
Output
Before modifying the list
$ID
[1] 1 2 3 4
$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"
$`Total Staff`
[1] 4
$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)
Output
Before concatenation of the new list
$ID
[1] 1 2 3 4
$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"
$`Total Staff`
[1] 4
append(my_numbers, 45)
my_numbers
Output
[1] 1 5 6 3 45
[1] 1 5 6 3
empList = list(
"ID" = empId,
"Names" = empName,
"Total Staff" = numberOfEmp
)
cat("Before deletion the list is\n")
print(empList)
Output
Before deletion the list is
$ID
[1] 1 2 3 4
$Names
[1] "Debi" "Sandeep" "Subham" "Shiba"
$`Total Staff`
[1] 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")
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)
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"
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" ))
print(gender)
Output
[1] female male other female
Levels: female male other
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
Example:
# R program to illustrate
# date function
Example:
# R program to illustrate
# [Link] function
[1] "2020-06-11"
[Link]()
[Link]() function is used to return the system's date and time.
Example:
# R program to illustrate
# [Link] function
[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:
Query Result
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)
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")
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)
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
repeat {
# Display menu
cat("3. Exit\n")
# Process choice
if (choice == 1) {
} else if (choice == 2) {
} else if (choice == 3) {
cat("Exiting program.\n")
} else {