Week 7
Aim:
☛ Implement different data structures in R (Vectors, Lists, Data Frames)
Solution :
Vectors in R:
In R, a vector is a basic data structure used to store multiple values of the same type.It is a one-dimensional data structure and can hold numeric, character, logical, or other atomic types.
In R, To create a vector, we use c() function(combine function) and in this, the elements are separated by a comma(,).
Syntax:
vect_name<- c(e1,e2,e3,..)
Example:
Filename: VectorEx.R
# Numeric vector
numbers <- c(10, 20, 30, 40)
print("Numeric Vector:")
print(numbers)
# Character vector
subjects <- c("Math", "Science", "History")
print("Character Vector:")
print(subjects)
# Logical vector
flags <- c(TRUE, FALSE, TRUE)
print("Logical Vector:")
print(flags)
Output:
[1] "Numeric Vector:"
[1] 10 20 30 40
[1] "Character Vector:"
[1] "Math" "Science" "History"
[1] "Logical Vector:"
[1] TRUE FALSE TRUE
Lists in R
A list is a collection of elements of different types. Lists are particularly useful when you need to store heterogeneous data.
In other words, A list is a flexible data structure that can store elements of different types, including numbers, characters, vectors, matrices, other lists, and even functions.
In R, To create a list, we use list() function and in this, the elements are separated by a comma(,).
Syntax:
list_name<- list(e1,e2,e3,..)
Example:
Filename: ListEx.R
# Creating a list with different types
student <- list(
name = "John",
age = 21,
scores = c(85, 90, 95),
pass = TRUE
)
print("List Example:")
print(student)
# Accessing list elements
print(paste("Student name is", student$name))
Output:
[1] "List Example:"
$name
[1] "John"
$age
[1] 21
$scores
[1] 85 90 95
$pass
[1] TRUE
[1] "Student name is John"
Data Frames in R
In R, A data frame is a two-dimensional array-like structure, or we can say it is a table in which each column contains the value of one variable, and row contains the set of value from each column. Data Frames are two-dimensional, heterogeneous data structures.
In R, To create a data frame we use the data.frame() function.
Syntax:
df <- data.frame(vector1, vector2, ..)
Example:
Filename: DataFrameEx.R
# Creating a data frame
students <- data.frame(
Names = c("Madhu", "Durga", "Naveen"),
Ages = c(22, 23, 21),
Scores = c(85.5, 90.0, 78.5)
)
print("Data Frame Example:")
print(students)
# Accessing a column
print("Names of students:")
print(students$Names)
Output:
[1] "Data Frame Example:"
Names Ages Scores
1 Madhu 22 85.5
2 Durga 23 90.0
3 Naveen 21 78.5
[1] "Names of students:"
[1] "Madhu" "Durga" "Naveen"
๐ป Run This R Program
Week 7
The selected R program is loaded
automatically into the editor.
Edit the program, provide input if required
and click Run.