0% found this document useful (0 votes)
8 views2 pages

Creating and Manipulating Matrices in R

The document contains R programming exercises focused on data frames, matrices, logical operators, and importing datasets. It includes tasks such as creating and exploring data frames, subsetting rows, adding columns, manipulating matrices, and performing matrix arithmetic. Additionally, it covers the use of logical operators and importing CSV and Excel files.

Uploaded by

Shifna Razack
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)
8 views2 pages

Creating and Manipulating Matrices in R

The document contains R programming exercises focused on data frames, matrices, logical operators, and importing datasets. It includes tasks such as creating and exploring data frames, subsetting rows, adding columns, manipulating matrices, and performing matrix arithmetic. Additionally, it covers the use of logical operators and importing CSV and Excel files.

Uploaded by

Shifna Razack
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

# R Programming Exercises with Solutions

# Topics: Data Frames, Matrices, Logical Operators, Importing Datasets

# Q1. Create and Explore a Data Frame

students <- [Link](

Name = c("Alice", "Bob", "Charlie"),

Age = c(20, 21, 19),

Marks = c(85, 92, 78)

students

str(students)

students$Marks

# Q2. Subset Rows Based on a Condition

students[students$Marks > 80, ]

# Q3. Add a New Column to a Data Frame

students$Passed <- students$Marks >= 80

students

# Q4. Create and Manipulate a Matrix

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

mat

mat[2, ] # 2nd row

mat[3, 1] # Element at row 3, column 1

# Q5. Assign Row and Column Names to a Matrix

rownames(mat) <- c("R1", "R2", "R3")

colnames(mat) <- c("C1", "C2", "C3")

mat
# Q6. Matrix Arithmetic

A <- matrix(c(1, 2, 3, 4), nrow = 2)

B <- matrix(c(5, 6, 7, 8), nrow = 2)

A+B

A*B

A %*% B

# Q7. Logical Operators on Vectors

v <- c(10, 15, 20, 25, 30)

v[v > 20]

v[v < 20] <- 0

# Q8. Logical Operators on Data Frames

students[students$Age < 21 & students$Marks > 80, "Name"]

# Q9. Import a CSV File

# Read CSV file (assumes file exists in working directory)

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

head(data)

summary(data)

# Q10. Import an Excel File

# [Link]("readxl") # Uncomment if not installed

library(readxl)

data <- read_excel("[Link]")

head(data)

You might also like