This content is protected. Copying or redistribution is not permitted.
Data Import, Export and Matrix Operations in R
Practical programs for file handling and user-defined matrix operations
Experiment 2: Data Import and Export Using Data Frames
Aim: To import and export CSV, XLS/XLSX and TXT data using R data frames.
Required packages
install.packages(c("readxl", "writexl"))
library(readxl)
library(writexl)
Create a sample data frame
student_data <- data.frame(
Roll_No = c(101, 102, 103, 104, 105),
Name = c("Amit", "Neha", "Ravi", "Priya", "Karan"),
Marks = c(78, 85, 69, 92, 81),
Grade = c("B", "A", "C", "A+", "A")
)
print(student_data)
CSV operations
# Export to CSV
write.csv(student_data, "student_data.csv", row.names = FALSE)
# Import from CSV
csv_data <- read.csv("student_data.csv")
print(csv_data)
str(csv_data)
TXT operations
# Export as a tab-separated text file
write.table(
student_data,
"student_data.txt",
sep = "\t",
row.names = FALSE,
quote = FALSE
)
# Import the tab-separated file
txt_data <- read.table(
"student_data.txt",
header = TRUE,
sep = "\t"
)
print(txt_data)
Excel operations
# Export to XLSX
write_xlsx(student_data, "student_data.xlsx")
# Import from XLS or XLSX
excel_data <- as.data.frame(
read_excel("student_data.xlsx", sheet = 1)
)
print(excel_data)
Note: Use
sep = "\t" for tab-separated,
sep = "," for comma-separated and sep = ""
for whitespace-separated text.
Result: CSV, Excel and TXT data was successfully imported and exported using R data frames.
Experiment 3: Matrix Operations Using Vector Concepts
Aim: To accept matrices from the user and perform addition, subtraction, multiplication, division, transpose and inverse operations.
| Operation | R syntax | Condition |
|---|---|---|
| Addition | A + B | Same dimensions |
| Subtraction | A - B | Same dimensions |
| Matrix multiplication | A %*% B | Columns of A = rows of B |
| Element-wise division | A / B | B contains no zero divisor |
| Transpose | t(A) | Any matrix |
| Inverse | solve(A) | Square and non-singular |
| Matrix division | A %*% solve(B) | B invertible; dimensions compatible |
Complete R program
input_matrix <- function(matrix_name) {
cat("\nEnter dimensions of matrix", matrix_name, "\n")
rows <- as.integer(readline("Number of rows: "))
columns <- as.integer(readline("Number of columns: "))
if (is.na(rows) || is.na(columns) || rows <= 0 || columns <= 0) {
stop("Rows and columns must be positive integers.")
}
total_elements <- rows * columns
cat("Enter", total_elements, "elements separated by spaces:\n")
values <- scan(what = numeric(), n = total_elements, quiet = TRUE)
if (length(values) != total_elements) {
stop("Incorrect number of matrix elements.")
}
matrix(values, nrow = rows, ncol = columns, byrow = TRUE)
}
A <- input_matrix("A")
B <- input_matrix("B")
cat("\nMatrix A:\n"); print(A)
cat("\nMatrix B:\n"); print(B)
if (all(dim(A) == dim(B))) {
cat("\nA + B:\n"); print(A + B)
cat("\nA - B:\n"); print(A - B)
cat("\nElement-wise A * B:\n"); print(A * B)
if (any(B == 0)) {
cat("\nElement-wise division is undefined where B is zero.\n")
} else {
cat("\nElement-wise A / B:\n"); print(A / B)
}
} else {
cat("\nElement-wise operations require equal dimensions.\n")
}
if (ncol(A) == nrow(B)) {
cat("\nMatrix product A %*% B:\n")
print(A %*% B)
} else {
cat("\nMatrix multiplication dimensions are incompatible.\n")
}
cat("\nTranspose of A:\n"); print(t(A))
cat("\nTranspose of B:\n"); print(t(B))
if (nrow(A) == ncol(A) && abs(det(A)) > .Machine$double.eps) {
cat("\nInverse of A:\n")
print(solve(A))
} else {
cat("\nA is not an invertible square matrix.\n")
}
if (nrow(B) == ncol(B) && abs(det(B)) > .Machine$double.eps) {
inverse_B <- solve(B)
cat("\nInverse of B:\n")
print(inverse_B)
if (ncol(A) == nrow(inverse_B)) {
cat("\nMatrix division A %*% inverse(B):\n")
print(A %*% inverse_B)
}
} else {
cat("\nB is not an invertible square matrix.\n")
}
Sample matrices
A = matrix(c(4, 7, 2, 6), nrow = 2, byrow = TRUE)
B = matrix(c(2, 1, 1, 3), nrow = 2, byrow = TRUE)
A + B
A - B
A %*% B
t(A)
solve(A)
A / B
A %*% solve(B)
Vector concept
The values are first stored as a vector and then arranged row-wise into a matrix. R applies arithmetic to corresponding elements without explicit loops.
values <- c(4, 7, 2, 6)
A <- matrix(values, nrow = 2, ncol = 2, byrow = TRUE)
print(A)
Result: The program successfully performs all dimensionally valid matrix operations using R's vectorized functions.