0% found this document useful (0 votes)
5 views33 pages

R Programming Basics: Vectors to Data Frames

Uploaded by

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

R Programming Basics: Vectors to Data Frames

Uploaded by

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

PARTICAL-1

QUESTION-1: Write a program in R to display "Welcome to R Programming" and check the current
working directory.
CODE:

# Display a message

print("Welcome to R Programming")

# Check the current working directory

getwd()

OUTPUT:

1
PARTICAL-2
QUESTION-2: Write a program in R to create different types of vectors (numeric, character, logical) and
perform vector operations (addition, subtraction, multiplication, division).

CODE:

# Creating different types of vectors

# Numeric vector

num_vec <- c(10, 20, 30, 40, 50)

print("Numeric Vector:")

print(num_vec)

# Character vector

char_vec <- c("R", "Python", "Java", "C++")

print("Character Vector:")

print(char_vec)

# Logical vector

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

print("Logical Vector:")

print(log_vec)

# Performing vector operations on numeric vectors

vec1 <- c(5, 10, 15)

vec2 <- c(2, 4, 6)

print("Vector Addition:")

print(vec1 + vec2)

print("Vector Subtraction:")

print(vec1 - vec2)

print("Vector Multiplication:")

print(vec1 * vec2)

2
print("Vector Division:")

print(vec1 / vec2)

OUTPUT:

3
PARTICAL-3
QUESTION-3: Write a program in R to create matrices using matrix(), rbind(), and cbind() functions and
perform operations such as transpose, addition, and multiplication.

CODE:

# Creating a matrix using matrix()

mat1 <- matrix(1:6, nrow = 2, ncol = 3) # 2x3 matrix

print("Matrix created using matrix():")

print(mat1)

# Creating a matrix using rbind()

row1 <- c(1, 2, 3)

row2 <- c(4, 5, 6)

mat2 <- rbind(row1, row2)

print("Matrix created using rbind():")

print(mat2)

# Creating a matrix using cbind()

col1 <- c(7, 8)

col2 <- c(9, 10)

col3 <- c(11, 12)

mat3 <- cbind(col1, col2, col3)

print("Matrix created using cbind():")

print(mat3)

# Matrix transpose

print("Transpose of mat1:")

print(t(mat1))

# Matrix addition (mat2 and mat3 are of same dimensions)

mat_add <- mat2 + mat3

4
print("Addition of mat2 and mat3:")

print(mat_add)

# Matrix multiplication (mat2 %*% t(mat3) to make dimensions compatible)

mat_mul <- mat2 %*% t(mat3)

print("Multiplication of mat2 and transpose of mat3:")

print(mat_mul)

OUTPUT:

5
6
PARTICAL-4

QUESTION-4: Write a program in R to create a list that contains a vector, a matrix, and a string. Access
and modify individual elements of the list.

CODE:

# Creating a list with a vector, a matrix, and a string

my_list <- list(

vec = c(10, 20, 30, 40),

mat = matrix(1:6, nrow = 2, ncol = 3),

msg = "Hello, R Programming!"

print("Original List:")

print(my_list)

# Accessing individual elements

print("Access vector element (2nd element):")

print(my_list$vec[2])

print("Access matrix element (row=2, col=3):")

print(my_list$mat[2, 3])

print("Access the string:")

print(my_list$msg)

# Modifying elements

my_list$vec[2] <- 200 # change 2nd element of vector

my_list$mat[1, 2] <- 99 # change element in matrix

my_list$msg <- "Modified String!" # change string

print("Modified List:")

print(my_list)

7
OUTPUT:

8
PARTICAL-5
QUESTION-5: Write a program in R to create a data frame containing student details (Name, Roll No.,
Marks) and perform operations like column/row selection and summary statistics.

CODE:

# Creating a data frame of student details

students <- [Link](

Name = c("Anita", "Rahul", "Priya", "Karan", "Sonia"),

Roll_No = c(101, 102, 103, 104, 105),

Marks = c(85, 92, 76, 88, 95)

print("Student Data Frame:")

print(students)

# Column selection

print("Selecting Name column:")

print(students$Name)

# Row selection (e.g., 2nd row)

print("Selecting 2nd row (Rahul's record):")

print(students[2, ])

# Selecting multiple columns (Name and Marks)

print("Selecting Name and Marks columns:")

print(students[, c("Name", "Marks")])

# Summary statistics of Marks

print("Summary of Marks column:")

print(summary(students$Marks))

# Mean, Min, Max of Marks

print(paste("Mean Marks:", mean(students$Marks)))

9
print(paste("Minimum Marks:", min(students$Marks)))

print(paste("Maximum Marks:", max(students$Marks)))

OUTPUT:

10
PARTICAL-6
QUESTION-6: Write a program in R to import data from a CSV file, display its structure, and export
modified data back to a new CSV file.

CODE:

# Step 1: Import data from a CSV file

# (Assuming we have a CSV file named "[Link]" with columns: Name, Roll_No, Marks)

students <- [Link]("[Link]")

# Step 2: Display the structure of the data

print("Structure of the imported data:")

str(students)

# Display the first few rows

print("First few rows of the data:")

head(students)

# Step 3: Modify the data

# Adding a new column 'Grade' based on Marks

students$Grade <- ifelse(students$Marks >= 90, "A",

ifelse(students$Marks >= 80, "B",

ifelse(students$Marks >= 70, "C", "D")))

print("Modified Data with Grades:")

print(students)

# Step 4: Export modified data to a new CSV file

[Link](students, "students_modified.csv", [Link] = FALSE)

print("Modified data exported to 'students_modified.csv'")

11
OUTPUT:

12
PARTICAL-7
QUESTION-7: Write a program in R to demonstrate the use of if, if-else, nested if, for, while, and repeat
control structures.

CODE:

# ---------------------------

# 1. if statement

# ---------------------------

num <- 10

if (num > 5) {

print("Number is greater than 5")

# ---------------------------

# 2. if-else statement

# ---------------------------

num <- 3

if (num %% 2 == 0) {

print("Number is even")

} else {

print("Number is odd")

# ---------------------------

# 3. Nested if statement

# ---------------------------

marks <- 85

if (marks >= 90) {

grade <- "A"

13
} else if (marks >= 75) {

grade <- "B"

} else if (marks >= 60) {

grade <- "C"

} else {

grade <- "D"

print(paste("Marks:", marks, "- Grade:", grade))

# ---------------------------

# 4. for loop

# ---------------------------

print("For loop: printing numbers 1 to 5")

for (i in 1:5) {

print(i)

# ---------------------------

# 5. while loop

# ---------------------------

print("While loop: printing numbers 5 to 1")

count <- 5

while (count > 0) {

print(count)

count <- count - 1

# ---------------------------

# 6. repeat loop

14
# ---------------------------

print("Repeat loop: printing numbers 1 to 3")

count <- 1

repeat {

print(count)

count <- count + 1

if (count > 3) {

break

OUTPUT:

15
PARTICAL-8
QUESTION-8: Write a program in R to define and use a user-defined function to calculate the area of a
circle and the factorial of a number.

CODE:

# ---------------------------

# 1. Function to calculate area of a circle

# ---------------------------

area_circle <- function(radius) {

area <- pi * radius^2

return(area)

# Test the function

r <- 5

cat("Area of a circle with radius", r, "is:", area_circle(r), "\n")

# ---------------------------

# 2. Function to calculate factorial of a number

# ---------------------------

factorial_num <- function(n) {

if (n == 0 || n == 1) {

return(1)

} else {

fact <- 1

for (i in 2:n) {

fact <- fact * i

return(fact)

16
}

# Test the function

num <- 6

cat("Factorial of", num, "is:", factorial_num(num), "\n")

OUTPUT:

17
PARTICAL-9
QUESTION-9: Write a program in R to demonstrate the use of apply(), lapply(), sapply(), and tapply()
functions on matrices and data frames.

CODE:

# ---------------------------

# 1. Using apply() on a matrix

# ---------------------------

mat <- matrix(1:9, nrow = 3, ncol = 3)

print("Matrix:")

print(mat)

# Sum of rows

row_sum <- apply(mat, 1, sum)

print("Sum of rows using apply():")

print(row_sum)

# Sum of columns

col_sum <- apply(mat, 2, sum)

print("Sum of columns using apply():")

print(col_sum)

# ---------------------------

# 2. Using lapply() on a data frame

# ---------------------------

df <- [Link](

Name = c("Anita", "Rahul", "Priya"),

Marks1 = c(85, 92, 76),

Marks2 = c(88, 95, 80)

18
print("Data Frame:")

print(df)

# lapply to calculate mean of numeric columns

mean_values <- lapply(df[, 2:3], mean)

print("Mean of numeric columns using lapply():")

print(mean_values)

# ---------------------------

# 3. Using sapply() on a data frame

# ---------------------------

mean_values_s <- sapply(df[, 2:3], mean)

print("Mean of numeric columns using sapply():")

print(mean_values_s)

# ---------------------------

# 4. Using tapply() on a vector with a grouping factor

# ---------------------------

marks <- c(85, 92, 76, 88, 95)

group <- c("A", "B", "A", "B", "A") # Grouping factor

mean_by_group <- tapply(marks, group, mean)

print("Mean marks by group using tapply():")

print(mean_by_group)

19
OUTPUT:

20
PARTICAL-10
QUESTION-10: Write a program in R to perform data manipulation using dplyr functions such as
select(), filter(), mutate(), arrange(), and summarise().

CODE:

# Load dplyr package

library(dplyr)

# Create a sample data frame

students <- [Link](

Name = c("Anita", "Rahul", "Priya", "Karan", "Sonia"),

Roll_No = c(101, 102, 103, 104, 105),

Marks = c(85, 92, 76, 88, 95),

Class = c("A", "B", "A", "B", "A")

print("Original Data Frame:")

print(students)

# 1. select() - Select specific columns

selected_df <- select(students, Name, Marks)

print("Selected Columns (Name, Marks):")

print(selected_df)

# 2. filter() - Filter rows based on condition

filtered_df <- filter(students, Marks > 85)

print("Students with Marks > 85:")

print(filtered_df)

# 3. mutate() - Add a new column (Grade based on Marks)

mutated_df <- mutate(students,

Grade = ifelse(Marks >= 90, "A",

21
ifelse(Marks >= 80, "B", "C")))

print("Data Frame with new column (Grade):")

print(mutated_df)

# 4. arrange() - Arrange rows by Marks descending

arranged_df <- arrange(students, desc(Marks))

print("Data Frame arranged by Marks descending:")

print(arranged_df)

# 5. summarise() - Summary statistics (average Marks by Class)

summary_df <- students %>%

group_by(Class) %>%

summarise(Average_Marks = mean(Marks))

print("Average Marks by Class:")

print(summary_df)

OUTPUT:

22
23
PARTICAL-11
QUESTION-11: Write a program in R to create visualizations using ggplot2 package: bar chart,
histogram, and scatter plot using built-in datasets.

CODE:

# Load ggplot2 package

library(ggplot2)

# ---------------------------

# 1. Bar chart (count of species in iris dataset)

# ---------------------------

print("Bar Chart: Count of each Species in iris dataset")

ggplot(data = iris, aes(x = Species, fill = Species)) +

geom_bar() +

ggtitle("Bar Chart of Iris Species") +

theme_minimal()

# ---------------------------

# 2. Histogram ([Link] in iris dataset)

# ---------------------------

print("Histogram: Distribution of [Link]")

ggplot(data = iris, aes(x = [Link])) +

geom_histogram(binwidth = 0.5, fill = "skyblue", color = "black") +

ggtitle("Histogram of [Link]") +

theme_minimal()

# ---------------------------

# 3. Scatter plot ([Link] vs [Link] colored by Species)

# ---------------------------

print("Scatter Plot: [Link] vs [Link]")

24
ggplot(data = iris, aes(x = [Link], y = [Link], color = Species)) +

geom_point(size = 3) +

ggtitle("Scatter Plot of Sepal Dimensions") +

theme_minimal()

OUTPUT:

25
PARTICAL-12
QUESTION-12: Write a program in R to calculate and interpret descriptive statistics: mean, median,
mode, standard deviation, and variance.

CODE:

# Sample data

marks <- c(85, 92, 76, 88, 95, 85, 92)

# 1. Mean

mean_val <- mean(marks)

cat("Mean:", mean_val, "\n")

# 2. Median

median_val <- median(marks)

cat("Median:", median_val, "\n")

# 3. Mode (custom function, as R does not have built-in mode function)

get_mode <- function(x) {

uniq_vals <- unique(x)

freq <- tabulate(match(x, uniq_vals))

mode_val <- uniq_vals[freq == max(freq)]

return(mode_val)

mode_val <- get_mode(marks)

cat("Mode:", mode_val, "\n")

# 4. Standard Deviation

sd_val <- sd(marks)

cat("Standard Deviation:", sd_val, "\n")

# 5. Variance

var_val <- var(marks)

26
cat("Variance:", var_val, "\n")

OUTPUT:

27
PARTICAL-13
QUESTION-13: Write a program in R to compute correlation between two variables and perform simple
linear regression analysis.

CODE:

# ---------------------------

# Sample Data

# ---------------------------

# Hours of study vs Exam scores

hours <- c(2, 3, 4, 5, 6, 7, 8)

scores <- c(50, 55, 60, 65, 70, 75, 80)

# ---------------------------

# 1. Correlation

# ---------------------------

correlation <- cor(hours, scores)

cat("Correlation between Hours and Scores:", correlation, "\n")

# ---------------------------

# 2. Simple Linear Regression

# ---------------------------

model <- lm(scores ~ hours)

summary(model)

# ---------------------------

# 3. Predicting new value

# ---------------------------

predicted <- predict(model, [Link](hours = 9))

cat("Predicted score for 9 hours of study:", predicted, "\n")

# ---------------------------

28
# 4. Plot regression line

# ---------------------------

plot(hours, scores, main = "Linear Regression: Hours vs Scores",

xlab = "Hours of Study", ylab = "Scores", pch = 19, col = "blue")

abline(model, col = "red", lwd = 2)

OUTPUT:

29
PARTICAL-14
QUESTION-14: Write a program in R to identify and handle missing values using [Link](), [Link](), and
[Link] options.

CODE:

# ---------------------------

# Sample Data with Missing Values

# ---------------------------

data <- c(10, 20, NA, 40, NA, 60, 70)

cat("Original Data:\n")

print(data)

# ---------------------------

# 1. Identify Missing Values using [Link]()

# ---------------------------

missing_flags <- [Link](data)

cat("\nIdentify Missing Values (TRUE = Missing):\n")

print(missing_flags)

# ---------------------------

# 2. Remove Missing Values using [Link]()

# ---------------------------

clean_data <- [Link](data)

cat("\nData after removing missing values ([Link]):\n")

print(clean_data)

# ---------------------------

# 3. Handle Missing Values using [Link] in calculations

# ---------------------------

sum_val <- sum(data, [Link] = TRUE)

30
mean_val <- mean(data, [Link] = TRUE)

cat("\nSum (ignoring NA):", sum_val, "\n")

cat("Mean (ignoring NA):", mean_val, "\n")

OUTPUT:

31
PRACTICAL-15
QUESTION-15: Write a program in R to create a pie chart and bar graph for a given set of categorical
data using base R plotting functions.

CODE:

# ---------------------------

# Sample categorical data

# ---------------------------

fruits <- c("Apple", "Banana", "Mango", "Orange", "Apple", "Banana", "Apple", "Mango", "Orange",
"Apple")

cat("Original Data:\n")

print(fruits)

# ---------------------------

# Create frequency table

# ---------------------------

fruit_counts <- table(fruits)

cat("\nFrequency of Fruits:\n")

print(fruit_counts)

# ---------------------------

# 1. Pie Chart

# ---------------------------

pie(fruit_counts,

main = "Pie Chart of Fruits",

col = rainbow(length(fruit_counts)))

# ---------------------------

# 2. Bar Graph

# ---------------------------

barplot(fruit_counts,

32
main = "Bar Graph of Fruits",

xlab = "Fruit Type",

ylab = "Count",

col = "skyblue",

border = "black")

Expected Console Output

csharp

Copy code

Original Data:

[1] "Apple" "Banana" "Mango" "Orange" "Apple" "Banana" "Apple"

[8] "Mango" "Orange" "Apple"

Frequency of Fruits:

fruits

Apple Banana Mango Orange

4 2 2 2

OUTPUT:

33

You might also like