M.C.A. Sem-3
Syllabus
Program | MasterofComputerApplications |
Semester | II |
CourseTitle | Java Programming Practical |
Course Code | LMC0221 |
CourseCredits | 02 |
Course Type | CorePractical Course |
- CourseSummary
Java, created by James Gosling at Sun Microsystems in 1991, is a versatile, object-oriented programming language. It compiles applications into bytecode, which can run on any platform via the Java Virtual Machine (JVM). Due to this portability, Java is often referred to as a WORA (Write Once, Run Anywhere) language. In today’s tech landscape, Java remains highly popular for developing lightweight, fast, and customizable applications. Syntax resembles JAVA, and automatic garbage collection simplifies memory management.Modular programs with reusable code.Concepts like inheritance, encapsulation, and polymorphism enhance practicality. It provides strong memory management and exception handling.
- CourseContents
Sr.No | Units | UnitOutcomes
After the successful completion of theunit,the learnershould beableto: |
1 | Unit 1:IntroductiontoOOP
· Introduction to data abstraction, encapsulation,polymorphism · Javaprogram:StructureandHelloWorldExample · DiscussiononJava keywords, data types and packages. |
1. DiscussOOPfeatures.
2. ImplementsimpleJavaprogram. 3. Discusskeywordsandother packages. |
2 | Unit2: Java Complier
· Detail of JDK. · Syntaxand semanticerrors |
1. DemonstrateJavaprogramsusing JVM, JRE.
2. UnderstandtheinstallationprocedureforJDK. |
3 | Unit3:Editor for Java Program
· IntroductiontoNetBeans · Installation of NetBeans · DifferentmenusandsettingsinNetBeans |
· Understand installation of NetBeans. |
4 | Unit4:ListofExperiments | |
i. | Write a java program to print even numbers from 1 to 10. | · To understand how to use NetBeans for java. Apply java concepts using it. |
ii. | Java Program to create a student class and its child class extstud (Derived Class). Use constructors in both the classes and display data with their methods. | · To create classes using inheritance concepts. |
iii. | Create an Abstract Class Shape and its derived class Circle and Rectangle. Print area of rectangle and circle for given parameters passed in their constructors with an overridden method GetArea(); | · To understand and apply concept of abstract class and methods. |
iv. | Write a Java Program to create a static member variable, static block and static inner class. Write a static method to display it. | · To understand the use of static variable, block and inner class. |
v. | Write a program to create an interface and a class which implements it. Show the use of default method and override it and attribute of interface as final. | · To understand and apply interface along with class. |
vi. | Write a program to find number is positive, negative or zero. | · To understand and apply “if else” control structure. |
vii. | Write a program to explain switch case in java. | · To understand and apply “switch case” control structure. |
viii | Write a Program to explain loops with array in java. | · To use different kind of loops and array in java. |
ix. | Write a java program to explain usage of try, catch and finally blocks in exception handling. | · To understand apply and concept of exception handling |
x. | Write a java program to demonstrate thread and print 1 to 10 numbers by each thread. Use multi thread and synchronize them. | · To understand the concept of threads. |
xi. | Write a java program to demonstrate GUI using JFrame and JButton. | · To create GUI applications using java. |
xii. | Write a java program using GUI features to add and subtract given two values using JFrame, JButton etc. | · To create GUI application for addition and subtraction of two values. |
xiii. | Write a java program to read a text file input.txt and write another text file output.txt. | · To understand serialization and create application to read and write data in text file. |
xiv | Write a java program to connect database available in MySQL and perform input output transaction with a file of database. | · To create application using jdbc driver and connectivity with database for data processing. |
xv | Write a java program to demonstrate socket program using Server and Client class in NetBeans 22. | · To understand and create client server based applications. |
- CourseResources
- EssentialReading
- Balagurusamy, E. (2019). Programming with Java: A Primer (5th ed.). McGraw-Hill Education.
- Malhotra, S., & Choudhary, S. (2014). Programming in Java (2nd ed.). Oxford University Press.
- Schildt, H. (2018). Java: The Complete Reference (11th ed.). McGraw-Hill Education.
- RecommendedReading
- Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley Professional.
- Sierra, K., & Bates, B. (2005). Head First Java (2nd ed.). O’Reilly Media.
- Pati, P. K., & Mohanty, R. (2016). Java Programming: A Comprehensive Introduction (1st ed.). Vikas Publishing House.
- Websites
- (n.d.). Object Oriented Programming in Java (University of California, San Diego). Retrieved from https://www.coursera.org/learn/object-oriented-java
- (n.d.). Introduction to Java Programming (Microsoft). Retrieved from https://www.edx.org/course/introduction-to-java-programming
- (n.d.). Learn Java. Retrieved from https://www.codecademy.com/learn/learn-java
- LinkedIn Learning. (n.d.). Java Essential Training (David Gassner). Retrieved from https://www.linkedin.com/learning/java-essential-training
- OtherElectronicResources
- CourseVideoLectureson LMS
Contents
Unit No | IntroductiontoObject-orientedprogramming | |
1 | Introduction …………………. | Page 1 |
2 | Java Development Kit…………………. | Page 3 |
3 | ListofExperiments…………………. | Page 6 |
4 | SamplePrograms…………………. | Page 9 |
5 | ExercisePrograms…………………. | Page22 |
6 | LabRecordSampleswithScreenshots…………………. | Page25 |
7 | RecommendedReading…………………. | Page28 |
Unit1: Introduction
Java is a widely-used programming language known for its versatility, portability, and security features. Java is a fully object-oriented programming language, and understanding its key Object-Oriented Programming (OOP) concepts is essential for effective Java development. Here are some key aspects of Java.
Classes and Objects:
Class: A class in Java is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of the class will have.
Object: An object is an instance of a class. It represents a real-world entity and encapsulates data (attributes) and behaviors (methods).
Encapsulation:
Encapsulation is the mechanism of bundling the data (attributes) and methods (behaviors) that operate on the data into a single unit (class). It helps in hiding the internal state of an object and restricting access to it.
Inheritance:
Inheritance allows one class (subclass or derived class) to inherit the properties and behaviors of another class (superclass or base class). It promotes code reusability and allows the creation of a hierarchy of classes.
Polymorphism:
Polymorphism means “many forms” and refers to the ability of objects to respond differently to the same method call. In Java, polymorphism is achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).
Abstraction:
Abstraction is the process of hiding the implementation details of methods and exposing only the functionality to the user. Abstract classes and interfaces in Java are used to achieve abstraction.
Association, Aggregation, and Composition:
These are relationships between classes:
Association: A relationship where one class is related to another class (e.g., a Car has a Driver).
Aggregation: A specialized form of association where an object of one class “has-a” relationship with another class, but it can exist independently (e.g., a University has Departments).
Composition: A stronger form of aggregation where one class owns another class and the owned class cannot exist independently (e.g., a Car has an Engine).
Interfaces and Abstract Classes:
Interface: An interface in Java defines a contract for classes to implement. It contains only method signatures (without implementations).
Abstract Class: An abstract class in Java cannot be instantiated on its own and may contain abstract methods (methods without implementations) and concrete methods.
Platform Independence: Java programs are compiled into an intermediate bytecode that can run on any Java Virtual Machine (JVM), regardless of the underlying computer architecture. This “write once, run anywhere” capability makes Java highly portable.
Object-Oriented: Java is fundamentally object-oriented, meaning it revolves around creating and manipulating objects. It supports principles such as inheritance, encapsulation, and polymorphism.
Syntax: Java syntax is largely influenced by C and C++, making it familiar to many programmers. It uses curly braces for code blocks and follows a strict structure for classes, methods, and variables.
Automatic Memory Management: Java uses a garbage collector to automatically manage memory allocation and deallocation, which helps developers avoid memory leaks and pointer-related errors.
Rich Standard Library: Java provides a vast standard library that includes classes and methods for tasks such as networking, I/O, data structures, and utilities, simplifying development by providing pre-written code for common functionalities.
Security: Java was designed with security in mind. The JVM sandboxing mechanism ensures that Java programs run securely and cannot harm the host system. This makes Java a popular choice for developing applications that require robust security measures.
Community and Ecosystem: Java has a large and active community of developers worldwide. It is used extensively in enterprise-level applications, web development (via technologies like Servlets and JSP), mobile applications (Android development), scientific computing, and more.
Unit2
Java Development Kit
Welcome to Apache NetBeans (Explained in Unit 3)
These installers include a local Java 22 JDK for the IDE to run on, offering a self-contained out-of-the-box experience. Additional JDK’s for projects may be registered and/or downloaded using Tools / Java Platforms in the IDE menu, supporting development of projects for Java 8 up to Java 22.
You can also install JAVA SE, JRE, SDK separately.
Installation of J2SDK.
Download and install Java for Windows computer.
Platform(s): Windows 8, Windows 7, Vista, Windows XP, Windows 2000,Windows 2003, Windows 2008 Server
Note: Installing Java requires that you can gain administrator access to Windows on your computer.
Download and Install
It is recommended; before you proceed with online installation you may want to disable your Internet firewall. In some cases, the default firewall settings are set to reject all automatic or online installations such as the Java online installation. If the firewall is not configured appropriately, it may stall the download/install operation of Java under certain conditions. Refer to your specific Internet firewall manual for instructions on how to disable your Internet Firewall.
- Go to the Manual download page
- Click on Windows Online
- The File Download dialog box appears prompting you to run or save the download file
To run the installer, click Run. - To save the file for later installation, click Save.
Choose the folder location and save the file to your local system.
Tip: Save the file to a known location on your computer, for example, to your desktop.
Double-click on the saved file to start the installation process. - The installation process starts. Click the Install button to accept the license terms and to continue with the installation.
Oracle has partnered with companies that offer various products. The installer may present you with option to install these programs when you install Java. After ensuring that the desired programs are selected, click the Next button to continue the installation.
A few brief dialogs confirm the last steps of the installation process; click Close on the last dialog. This will complete Java installation process.
Required Software/ Software Tool: –
Platform(s): Windows 8, Windows 7, Vista, Windows XP, Windows 2000, Windows 2003, Windows 2008 Server
Java version(s): 6.0, 7.0 (jdk1.6, jdk1.7)
Editor: – Net Beans IDE 6.9.1
Database: – Oracle9i / MySQL
Web server: – Apache Tomcat 5.5
The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes a variety of tools and components needed for Java development. Here’s an overview of the key components and features of the JDK:
Key Components of the JDK
Java Compiler (javac)
Converts Java source code (.java files) into bytecode (.class files) that can be executed by the Java Virtual Machine (JVM).
Run the Java Program
To run the compiled Java program, use the java command followed by the name of the class containing the main method, without the .class extension:
Java Runtime Environment (JRE)
Includes the JVM, core libraries, and other components to run applications written in Java.
Java Virtual Machine (JVM)
The engine that runs Java bytecode. It provides platform independence by allowing Java programs to run on any device or operating system.
Java Debugger (jdb)
A tool for finding and fixing bugs in Java programs.
Java Archive Tool (jar)
Packages multiple files into a single JAR file, which can be used for deployment.
Java Documentation Generator (javadoc)
Generates HTML documentation from Java source code comments.
Other Tools
Includes a variety of other utilities and tools such as javap (class file disassembler), jconsole (JMX-compliant monitoring and management tool), and more.
Set up Environment Variables:
- Set the JAVA_HOME environment variable to point to the JDK installation directory.
- Add the bin directory within the JDK installation directory to the PATH environment variable.
General Guidelines
Ineachlabsession,aspecificfeatureofOOPusingJava iscovered.Attempteachexerciserelatedto the sample list of experiments mentioned in the list. Each program must include generalcomments such as name, date of program development, description of the program, function, ablock of statements, etc. Every Java program must be interactive and the documentation forinput/outputmustbeclear.Eachlabassignmentmustbesubmittedintheformofalabrecord.Thelab record must include problem definition, algorithm/concept used, source code, and sampleinput/output.Thereare12unitsinthislaboratory.Anindicativelistofexperimentsis mentionedthatcoversmostoftheOOPfeatures. Foreachunitoneexperimentismentionedinthelist.Somemoreadditionalexercisesaregiveninthelatersections.
Unit 3
Editor for Java Program – NetBeans 22 with JDK 22
- Download NetBeans
- Install NetBeans
- Click on New Project
- Select Java Application and click next
- Select Java Application and click next
Unit4
Anindicativelistof experiments isgiven inTable 1.2.
ListofExperiments
Topic Covered | ProblemDefinition |
1 | Write a Java Program to find roots of quadratic equations. |
2 | Write a Java program to create a class known as “BankAccount” with methods called deposit() and withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method to prevent withdrawals if the account balance falls below one hundred. |
3 | Write a Java Program to create an abstract class named shape that contains two integers and an empty method named printArea.Provide three classes named Rectangle,Triangle and Circle subclass that each one of the classes extends the Class Shape. Each one of the classes contains only the method printArea() that prints the area of Shape. |
4 | Write a java program to computer the sum of array elements. |
5 | Write a java program to explain use of interface with any suitable problem. |
6 | Write a java program to find greatest among given three values. |
7 | Write a java program that implements Selection sort algorithm for sorting a list of numbers in ascending order. |
8 | Write a Program that creates User Interface to perform Integer Divisions.The user enters two numbers in text fields, Num1 and Num2.The division of Num1 and Num2 is displayed in the result field when the divide button clicked. If Num1 or Num2 were not integer, the program would throw a NumberFormatException,If Num2 is Zero, and the program would throw an Athematic Exception. Display theException in message box. |
9 | Write a JAVA program that creates threads by extending Thread class. First thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable) |
10 | Write a java program that loads names and phone numbers from the text file where data is organized as one line per record and each field in record are separated by any delimiter. |
Table1.2List of experiments
SamplePrograms
EXPERIMENT-1
Problemdefinition:Write a Java program to print even numbers from 1 to 10.
SourceProgram:
package com.priy.even;
/** * * @author priya */ public class EVEN { public static void main(String[] args) { for ( int i=1; i<=10 ; i++) if ( i % 2 == 0 ) System.out.println(“Even No:”+i); } } |
Output:
Even No:2 Even No:4 Even No:6 Even No:8 Even No:10 |
MCQ
1. Number of primitive data types in Java are?
a) 6
b) 7
c) 8
d) 9
Ans. c
2. What is the size of float and double in Java?
a) 32 and 64
b) 32 and 32
c) 64 and 64
d) 64 and 32
Ans. a
3. Automatic type conversion is possible in which of the possible cases?
a) Byte to int
b) Int to long
c) Long to int
d) Short to int
Ans. B
4. When is the object created with new keyword?
a) At run time
b) At compile time
c) Depends on the code
d) None
Ans. a
5. Identify the correct definition of a package.
a) A package is a collection of editing tools
b) A package is a collection of classes
c) A package is a collection of classes and interfaces
d) A package is a collection of interfaces
Ans. c
6. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
Ans. c
EXPERIMENT-2
Problemdefinition:Java Program to create a student class and its child class extstud (Derived Class). Use constructors in both the classes and display data with their methods.
Source Program
package stud;
public class student { public String stdname; public int rollno; public student(String n,int r) { this.stdname = n; this.rollno = r; } public void dispstud() { System.out.println(“Student Name: “+this.stdname); System.out.println(“Student Rollno: “+this.rollno); }} package stud; public class extstud extends student{ public int extrafees; public extstud(String n,int r,int f) { super(n,r); extrafees = f; } public void extstuddisp() { super.dispstud(); System.out.println(“Extra Fees: “+ this.extrafees); } } package com.priy.priy; import stud.extstud; public class PRIY { public static void main(String[] args) { extstud obj1 = new extstud (“Trupti”,12,3000); obj1.extstuddisp(); } } |
Output:
Student Name: Trupti
Student Rollno: 12
Extra Fees: 3000
MCQ
1. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
Ans. c
2. What is not the use of “this” keyword in Java?
a) Referring to the instance variable when a local variable has the same name
b) Passing itself to the method of the same class
c) Passing itself to another method
d) Calling another constructor in constructor chaining
Ans. b
3. Identify the modifier which cannot be used for constructor.
a) public
b) protected
c) private
d) static
Ans. D
4. What is the implicit return type of constructor?
a) No return type
b) A class object in which it is defined
c) void
d) None
Ans. B
5. When is the finalize() method called?
a) Before garbage collection
b) Before an object goes out of scope
c) Before a variable goes out of scope
d) None
Ans. a
6. What is the extension of compiled java classes?
a) .txt
b) .js
c) .class
d) .java
Ans. c
EXPERIMENT3
ProblemDefinition:Create an Abstract Class Shape and its derived class Circle and Rectangle. Print area of rectangle and circle for given parameters passed in their constructors with an overridden method GetArea();
SourceProgram
package com.priy.abstclass;
// define abstract class
public abstract class Shape {
//define abstract method
public abstract double GetArea();
}
package com.priy.abstclass;
public class Circle extends Shape {
private double radius;
public Circle(double r) {
this.radius = r;
}
@Override
public double GetArea() {
return Math.PI * radius * radius;
}
}
package com.priy.abstclass;
public class Rectangle extends Shape{
private double width;
private double length;
public Rectangle(double w,double l)
{
this.width = w;
this.length = l;
}
@Override
public double GetArea() {
return width * length;
}
}
package com.priy.abstclass;
public class AbstClass {
public static void main(String[] args) {
Circle c = new Circle(5);
Rectangle r = new Rectangle (10,12);
System.out.println(“Area of Circle :”+ c.GetArea());
System.out.println(“Area of Rectangle :”+ r.GetArea());
}
}
SampleInput/Output
Output:
Area of Circle :78.53981633974483
Area of Rectangle :120.0
MCQ
1. What is an abstract class?
A) A class that cannot have any methods
B) A class that cannot have any properties
C) A class that cannot be instantiated and can have abstract methods
D) A class that must be instantiated to use its methods
Answer: C
2. What is an abstract method?
A) A method that is fully implemented in the abstract class
B) A method that is declared without an implementation
C) A method that can only be called from other abstract methods
D) A method that can only be used within the abstract class
Answer: B
3. What must a subclass do if it inherits from an abstract class containing abstract methods?
A) It must implement all of the abstract methods of the superclass
B) It can ignore the abstract methods of the superclass
C) It must remain abstract itself
D) It cannot add any new methods of its own
Answer: A
4. Can an abstract class have a constructor?
A) Yes, and it can be called using the super keyword from subclasses.
B) No, an abstract class cannot have a constructor.
C) Yes, but it cannot be used by any subclasses.
D) No, constructors are only for concrete classes.
Answer: A
5. In Java, which keyword is used to declare a class as abstract?
A) virtual
B) abstract
C) interface
D) extends
Answer: B
6. Can abstract classes implement interfaces?
A) No, abstract classes cannot implement interfaces.
B) Yes, but they must provide implementations for all interface methods.
C) Yes, and they can choose to implement none, some, or all of the interface methods.
D) Yes, but only if the interface methods are declared abstract.
Answer: C
EXPERIMENT4
ProblemDefinition:Write a Java Program to create a static member variable, static block and static inner class. Write a static method to display it.
package com.priy.astat;
public class Astat { static int a = 10; /* A static method belongs to the class rather than any instance of the class. It can be called without creating an instance of the class. Static methods can access static variables and other static methods directly. They cannot access instance variables or instance methods directly because they do not operate on a specific instance. */ /* Static blocks are used for static initialization of a class. They run once when the class is first loaded into memory. */ /* A static inner class (nested static class) can be instantiated without an instance of the outer class. It can access static members of the outer class but cannot access instance members. */ static class B { static void smethod() { /* A static variable is shared among all instances of a class. It can be accessed directly using the class name, without needing to instantiate the class. */ System.out.println(“This is static method”); System.out.println(“Value of a:” + Astat.a); } } public static void main(String[] args) { Astat.B.smethod(); } } |
SourceProgram:
This is static method
Value of a:10 |
SampleInput/Output
MCQ
1. What is the role of a constructor in classes?
a) To modify the data whenever required
b) To destroy an object
c) To initialize the data members of an object when it is created
d) To call private functions from the outer world
Ans. c
2. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors
Ans. d
3. How constructors are different from other member functions of the class?
a) Constructor has the same name as the class itself
b) Constructors do not return anything
c) Constructors are automatically called when an object is created
d) All of the mentioned
Ans. d
4. How many types of constructors are there in JAVA?
a) 1
b) 2
c) 3
d) 4
Ans. c
5. When destructors are called?
a) When a program ends
b) When a function ends
c) When a delete operator is used
d) All of the mentioned
Ans. d
6. What is the difference between constructors and destructors?
a) They have a different function name
b) Constructors does not have return type whereas destructors do have
c) Constructors allow function parameters whereas destructors do not
d) Constructors does not function parameters
Ans. c
EXPERIMENT – 5
Problem Definition: Write a program to create an interface and a class which implements it. Show the use of default method and override it and attribute of interface as final.
package com.priy.intfabc;
public interface human {
public int age=56;
default void humanprint() {
System.out.println(“I am a human”);
}
}
package com.priy.intfabc;
public interface man extends human {
public void husband();
public void son();
}
package com.priy.intfabc;
public class Teacher implements man {
@Override
public void humanprint()
{
System.out.println(“I am a human – overriding default method”);
}
@Override
public void husband() {
System.out.println(“I am a husband”);
}
@Override
public void son() {
System.out.println(“I am a son”);
}
}
package com.priy.intfabc;
/* Interface fields are public, static and final by default,
and the methods are public and abstract. */
/* a class extends another class, an interface extends another interface,
but a class implements an interface.*/
public class IntfABC {
public static void main(String[] args) {
Teacher a = new Teacher();
// a.age= 60; not possible
System.out.println(a.age );
a.humanprint();
a.husband();
a.son();
}
}
Output:
56
I am a human – overriding default method
I am a husband
I am a son
MCQ
1. What is an interface in Java?
A) A class that can have concrete methods
B) A class that can be instantiated
C) A reference type, similar to a class, that can contain only abstract methods, default methods, static methods, and final variables
D) A class that can extend multiple classes
Answer: C
2. Which keyword is used to implement an interface in a class in Java?
A) extends
B) implements
C) interface
D) inherits
Answer: B
3. Can an interface in Java contain instance variables?
A) Yes, but they must be initialized
B) No, it can only contain final variables
C) Yes, and they can be modified by implementing classes
D) No, it cannot contain any variables
Answer: B
4. Which of the following can an interface contain in Java?
A) Abstract methods
B) Default methods
C) Static methods
D) All of the above
Answer: D
5. What is the purpose of a default method in an interface?
A) To provide a default implementation for all classes
B) To allow methods to be overridden
C) To provide a common method implementation without affecting existing classes that implement the interface
D) To declare a method as optional
Answer: C
6. Can an interface extend another interface in Java?
A) Yes, and it can extend multiple interfaces
B) No, interfaces cannot extend other interfaces
C) Yes, but only one interface
D) No, interfaces can only implement other interfaces
Answer: A
EXPERIMENT – 6
Problem Definition: Write a program to find number is positive, negative or zero.
SourceProgram:
package com.priy.contstrut;
import java.util.Scanner;
public class ContStrut {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter an integer :”);
int num = scanner.nextInt();
if ( num> 0 ) {
System.out.println(“Number is Positive”);
}
else if (num == 0) {
System.out.println(“Number is zero”);
}
else {
System.out.println(“Number is Negative”);
}
}
}
Output:
Enter an integer :-5
Number is Negative
Enter an integer :0
Number is zero
Enter an integer :5
Number is Positive
MCQ
1. Which of the following is a valid control structure in Java?
A) for
B) while
C) do-while
D) All of the above
Answer: D
2. Which of the following loops is guaranteed to execute at least once?
A) for
B) while
C) do-while
D) None of the above
Answer: C
3. What is the purpose of the break statement in a loop?
A) To skip the current iteration and proceed to the next iteration
B) To exit the loop immediately
C) To skip the rest of the code inside the loop for the current iteration
D) To pause the loop execution
4. Answer: B
Which control structure is used to handle exceptions in Java?
A) try-catch
B) if-else
C) for
D) while
5. Answer: A
Which of the following statements about the switch statement is true?
A) It can only evaluate int values
B) It can evaluate int, char, byte, short, String, and enum types
C) It can evaluate boolean values
D) It cannot have a default case
Answer: B
6. Which of the following is true about the continue statement?
A) It exits the loop immediately
B) It skips the current iteration and proceeds to the next iteration of the loop
C) It pauses the loop execution
D) It terminates the program
Answer: B
EXPERIMENT–7
ProblemDefinition:Write a program to explain switch case in java.
SourceProgram
package com.priy.contstrut;
import java.util.Scanner;
public class ContStrut {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter number of day from (1 – 7) :”);
int day = scanner.nextInt();
switch(day)
{
case 1:
System.out.print(“Given Day is Sunday”);
break;
case 2:
System.out.print(“Given Day is Monday”);
break;
case 3:
System.out.print(“Given Day is Tuesday”);
break;
case 4:
System.out.print(“Given Day is Wednesday”);
break;
case 5:
System.out.print(“Given Day is Thursday”);
break;
case 6:
System.out.print(“Given Day is Friday”);
break;
case 7:
System.out.print(“Given Day is Saturday”);
break;
default :
System.out.print(“Your input is wrong”);
}
}
}
Output:
Enter number of day from (1 – 7) :2
Given Day is Monday
MCQ
1. Which of the following types can be evaluated in a switch statement in Java?
A) int
B) char
C) String
D) All of the above
Answer: D
2. Which keyword is used to exit a switch statement in Java?
A) exit
B) continue
C) break
D) return
Answer: C
3. What happens if there is no break statement in a switch case?
A) The code will not compile
B) The program will exit the switch statement after the current case
C) The execution will fall through to the next case
D) The default case will be executed
Answer: C
4. Is it mandatory to have a default case in a switch statement?
A) Yes
B) No
Answer: B
5. Can a switch statement evaluate a boolean value?
A) Yes
B) No
Answer: B
6. What is the purpose of the default case in a switch statement?
A) To handle a situation where no case matches the switch expression
B) To terminate the switch statement
C) To provide a value for the switch expression
D) To ignore unmatched cases
Answer: A
EXPERIMENT-8
ProblemDefinition:Write a Program to explain loops with array in java.
SourceProgram
package com.priy.contstrut;
import java.util.Scanner; // program to understand loops in java public class ContStrut { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter value of counter i :”); for ( int i = scanner.nextInt(); i <= 10 ;i++) { System.out.println(“i = “+i); } int i = 5; while ( i <= 15){ System.out.println(“i = “+ i++); } do { System.out.println(“i = “+ i++); } while ( i <= 20); int[] numbers = {30,32,35,36,42}; for(int n : numbers) { System.out.println(“n = “+ n++); } } } |
Enter value of counter i :7
i = 7 i = 8 i = 9 i = 10 i = 5 i = 6 i = 7 i = 8 i = 9 i = 10 i = 11 i = 12 i = 13 i = 14 i = 15 i = 16 i = 17 i = 18 i = 19 i = 20 n = 30 n = 32 n = 35 n = 36 n = 42 |
SampleInput/Output
MCQ
- Select the valid statement.
a) char[] ch = new char(5)
b) char[] ch = new char[5]
c) char[] ch = new char()
d) char[] ch = new char[]
Ans. b
- When an array is passed to a method, what does the method receive?
a) The reference of the array
b) A copy of the array
c) Length of the array
d) Copy of the first element
Ans. a
- Select the valid statement to declare and initialize an array.
a) int[] A = {}
b) int[] A = {1, 2, 3}
c) int[] A = (1, 2, 3)
d) int[][] A = {1, 2, 3}
Ans. b
- Arrays in java are-
a) Object references
b) objects
c) Primitive data type
d) None
Ans. b
- Which of the following statements is true about the while loop?
A) The loop is guaranteed to execute at least once.
B) The loop might not execute at all if the condition is false initially.
C) The loop always executes a fixed number of times.
D) The loop cannot be exited using a break statement.
Answer: B
- Which of the following statements is true about the for loop?
A) It is used for an infinite loop only.
B) It can have an initialization, condition, and increment/decrement in one line.
C) It cannot be used with arrays.
D) It cannot be nested.
Answer: B
EXPERIMENT – 9
Problem definition: Write a java program to explain usage of try, catch and finally blocks in exception handling.
Source Program
package com.priy.ehand;
public class Ehand { public static void main(String[] args) { try { int r = divide(10,0); // divide by zero // int r = divide(10,2); // Result = 5 System.out.println(“Result =” + r); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } finally { System.out.println(“finally block always executed”); } } public static int divide(int a, int b) throws ArithmeticException { if (b==0) { throw new ArithmeticException(“Error – Divide by zero”); } else return a/b; } } |
Error – Divide by zero
finally block always executed Result =5 finally block always executed |
SampleInput/Output
MCQ
- Exception created by try block is caught in which block
a) catch
b) throw
c) final
d) none
Ans. a
- What is the use of the throws keyword in Java?
A) To declare that a method can throw exceptions
B) To handle an exception
C) To rethrow an exception
D) To catch an exception
Answer: A
- Which of the following is not a runtime exception in Java?
A) ClassCastException
B) IllegalArgumentException
C) IOException
D) NullPointerException
Answer: C
- Which of the following exception is thrown when divided by zero statement is executed?
a) NullPointerException
b) NumberFormatException
c) ArithmeticException
d) None
Ans. c
- Which of the following exceptions is thrown when a method receives an invalid argument?
A) IllegalArgumentException
B) ArrayIndexOutOfBoundsException
C) NullPointerException
D) ClassCastException
Answer: A
- Can a finally block be used without a catch block in Java?
A) Yes
B) No
Answer: A
EXPERIMENT – 10
Problem definition: Write a java program to demonstrate thread and print 1 to 10 numbers by each thread. Use multi thread and synchronize them.
Source Program
package com.priy.thproj;
public class PrintN extends Thread { String ThreadName; PrintN(String tn) { ThreadName = tn; } @Override public void run() { for (int i=1; i<=10 ;i++) { System.out.println(ThreadName+ “:” + i); } try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println(“Thread Interrupted”); } } } ___________________________________________________________________________ package com.priy.thproj; public class THPROJ { public static void main(String[] args) { PrintN t1 = new PrintN ( “Thread-1”); PrintN t2 = new PrintN ( “Thread-2”); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch(InterruptedException e) { System.out.println(“Thread Interrupted”); } System.out.println(“Done”); } } |
Thread-2:1
Thread-2:2 Thread-2:3 Thread-2:4 Thread-2:5 Thread-2:6 Thread-2:7 Thread-2:8 Thread-1:1 Thread-2:9 Thread-2:10 Thread-1:2 Thread-1:3 Thread-1:4 Thread-1:5 Thread-1:6 Thread-1:7 Thread-1:8 Thread-1:9 Thread-1:10 Done |
SampleInput/Output
MCQ
- Which class is used to create a thread in Java?
A) Runnable
B) Thread
C) Callable
D) Executor
Answer: B
- Which interface must be implemented to create a thread in Java?
A) Thread
B) Callable
C) Runnable
D) Executor
Answer: C
- What method must be overridden when implementing the Runnable interface?
A) start()
B) run()
C) execute()
D) call()
Answer: B
- Which of the following methods is used to start a thread execution?
A) run()
B) execute()
C) start()
D) begin()
Answer: C
- What is the state of a thread when it is executing?
A) Runnable
B) Running
C) Waiting
D) Blocked
Answer: B
- Which method is used to pause the execution of a thread for a specified period?
A) wait()
B) sleep()
C) pause()
D) stop()
Answer: B
EXPERIMENT- 11
Problem definition: Write a java program to demonstrate GUI using JFrame and JButton.
Source Program
package com.priy.swingex;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author priya */ public class SwingEx { public static void demoGui() { //creating the frame JFrame frame = new JFrame(“Swing Example”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,200); //creating a button JButton button = new JButton(“Click Here”); button.addActionListener(e -> JOptionPane.showMessageDialog(frame,frame.getContentPane().add(button))); // Adding the button on the frame frame.getContentPane().add(button); //Display the window frame.setVisible(true); } public static void main(String[] args) { demoGui(); } } |
Sample Input / Output
MCQ
1. Which method is used to close a JFrame when the close button is clicked?
A) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
B) setCloseOperation(JFrame.EXIT_ON_CLOSE)
C) setOperation(JFrame.EXIT_ON_CLOSE)
D) setWindowClose(JFrame.EXIT_ON_CLOSE)
Answer: A
2. What is JButton in Java Swing?
A) A class that represents a text field
B) A class that represents a button
C) A class that represents a window
D) A class that represents a panel
Answer: B
3. Which method is used to set the text of a JButton?
A) setText()
B) setLabel()
C) setButtonText()
D) setCaption()
Answer: A
4. How do you add a JButton to a JFrame?
A) frame.add(button)
B) frame.insert(button)
C) frame.put(button)
D) frame.append(button)
Answer: A
5. Which interface must be implemented to handle button click events in Java Swing?
A) ActionListener
B) MouseListener
C) KeyListener
D) WindowListener
Answer: A
6. How do you register an ActionListener with a JButton?
A) button.addActionListener(listener)
B) button.setActionListener(listener)
C) button.registerActionListener(listener)
D) button.addListener(listener)
Answer: A
EXPERIMENT – 12
Problem definition: Write a java program using GUI features to add and subtract given two values using JFrame, JButton etc.
Source Program
package com.priy.additionsubtraction;
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class AdditionSubtraction extends JFrame implements ActionListener { private JTextField num1Field; private JTextField num2Field; private JLabel resultLabel; public AdditionSubtraction(){ setTitle(“Addition and Subtraction”); setSize(300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Create components JLabel num1Label = new JLabel(“Number 1:”); JLabel num2Label = new JLabel(“Number 2:”); num1Field = new JTextField(10); num2Field = new JTextField(10); JButton addButton = new JButton(“Add”); JButton subtractButton = new JButton(“Subtract”); resultLabel = new JLabel(“Result: “); // Add action listeners addButton.addActionListener(this); subtractButton.addActionListener(this); // Set layout and add components setLayout(new GridLayout (5,2)); add(num1Label); add(num1Field); add(num2Label); add(num2Field); add(addButton); add(subtractButton); add(resultLabel); } |
Sample Input / Output
@Override
public void actionPerformed(ActionEvent e) { try { double num1 = Double.parseDouble(num1Field.getText()); double num2 = Double.parseDouble(num2Field.getText()); String command = e.getActionCommand(); if (command.equals(“Add”)) { double result = num1 + num2; resultLabel.setText (“Result: ” + result); } else if (command.equals (“Subtract”)) { double result = num1 – num2; resultLabel.setText (“Result: ” + result); } } catch (NumberFormatException ex) { resultLabel.setText(“Invalid input!”); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { AdditionSubtraction app = new AdditionSubtraction(); app.setVisible(true); }); } } |
MCQ
1. Which of the following is the base class for all Swing components?
A) Component
B) Container
C) JComponent
D) SwingComponent
Answer: C
2. Which layout manager arranges components in a single row or column?
A) FlowLayout
B) BorderLayout
C) GridLayout
D) BoxLayout
Answer: D
3. Which method is used to make a JFrame visible?
A) setDisplay(true)
B) setVisible(true)
C) show()
D) display()
Answer: B
4. Which component is used to create a dialog box in Java Swing?
A) JDialog
B) JOptionPane
C) JMessageBox
D) JDialogBox
Answer: A
5. Which method is used to add a component to a JPanel?
A) panel.addComponent(component)
B) panel.addItem(component)
C) panel.add(component)
D) panel.insert(component)
Answer: C
6. What is the default layout manager for a JPanel?
A) FlowLayout
B) BorderLayout
C) GridLayout
D) CardLayout
Answer: A
EXPERIMENT – 13
Problem definition: Write a java program to read a text file input.txt and write another text file output.txt.
import java.io.*;
public class IOPROJECT { public static void main(String[] args) { // File paths String inputFilePath = “input.txt”; String outputFilePath = “output.txt”; // Read from a file try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) { String line; while ((line = reader.readLine()) != null) { System.out.println(“Read from file: ” + line); } } catch (IOException e) { System.err.println(“Error reading from file: ” + e.getMessage()); } // Write to a file try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) { writer.write(“Hello, World!”); writer.newLine(); writer.write(“This is a sample file output.”); System.out.println(“Successfully wrote to the file.”); } catch (IOException e) { System.err.println(“Error writing to file: ” + e.getMessage()); } } } |
Source Program
Sample Input / Output
Read from file: I love India.
Read from file: I love you all.
Successfully wrote to the file.
MCQ
1. Which of the following is used to create a new file if it does not exist?
A) File.createNewFile()
B) File.newFile()
C) FileWriter.create()
D) File.create()
Answer: A
2. Which method of the Files class can be used to read all lines from a file as a List?
A) readAllLines()
B) readLines()
C) getLines()
D) fetchLines()
Answer: A
3. How do you write an array of strings to a file using Files class?
A) Files.write(Path, List, StandardCharsets.UTF_8)
B) Files.write(Path, String[], StandardCharsets.UTF_8)
C) Files.write(Path, Arrays.asList(String[]), StandardCharsets.UTF_8)
D) Files.write(Path, String[], StandardCharsets.UTF_8)
Answer: C
4. What does the FileInputStream class do?
A) Reads data from a file in binary format
B) Writes data to a file in text format
C) Reads and writes data from/to a file in text format
D) Creates a new file
Answer: A
5. Which class can be used to read binary data from a file?
A) FileReader
B) BufferedReader
C) DataInputStream
D) PrintWriter
Answer: C
6. How can you append data to an existing file using FileWriter?
A) new FileWriter(“file.txt”, true)
B) new FileWriter(“file.txt”, false)
C) new FileWriter(“file.txt”)
D) new FileWriter(“file.txt”, append=true)
Answer: A
EXPERIMENT – 14
Problem definition: Write a java program to connect database available in MySQL and perform input output transaction with a file of database.
To create a Java program that connects to a MySQL database, you need to follow these steps:
Set up MySQL:
Ensure you have MySQL installed and running.
Create a database and a table with some sample data.
Download the MySQL Connector/J:
Download the MySQL Connector/J from the official MySQL website. (MySQL :: Download Connector/J)
Add the MySQL Connector/J JAR file to your NetBeans project.
Create a new Java project in NetBeans and write the code:
import java.sql.Connection;
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import com.mysql.cj.jdbc.Driver; public class MySQLJDBCExample { public static void main(String[] args) { // Database credentials String jdbcURL = “jdbc:mysql://localhost:3306/example_db?zeroDateTimeBehavior=CONVERT_TO_NULL”; String username = “root”; String password = “root”; // Change this to your MySQL root password Connection connection = null; Statement statement = null; try { // Establish connection to the database connection = DriverManager.getConnection(jdbcURL, username, password); if (connection != null) { System.out.println(“Connected to the database!”); // Create a statement object to perform queries statement = connection.createStatement(); // Execute a query to retrieve data String sql = “SELECT * FROM users”; ResultSet resultSet = statement.executeQuery(sql); |
Source Program
// Process the result set
while (resultSet.next()) { int id = resultSet.getInt(“id”); String name = resultSet.getString(“name”); String email = resultSet.getString(“email”); System.out.println(“ID: ” + id + “, Name: ” + name + “, Email: ” + email); } // Close the result set resultSet.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the statement and connection if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (Exception e) { e.printStackTrace(); } } } } |
Sample Input / Output
With connection string
jdbcURL = “jdbc:mysql://localhost:3306/example_db?zeroDateTimeBehavior=CONVERT_TO_NULL”;
Connected to the database!
Connected to the database!
ID: 1, Name: Ram, Email: Ram@example.com
ID: 2, Name: Sit, Email: Sita@example.com
With connection string
jdbcURL = “jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=CONVERT_TO_NULL”;
Connected to the database!
ID: 1, Name: Ghanshyan, Email: ghan@example.com
ID: 2, Name: radha, Email: radha@example.com
MCQ
1. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
Ans. d
2. Which class in Java provides the connection to the database?
A) Statement
B) Connection
C) DriverManager
D) ResultSet
Answer: B
3. How do you load the MySQL JDBC driver in Java?
A) Class.forName(“com.mysql.jdbc.Driver”)
B) DriverManager.loadDriver(“com.mysql.jdbc.Driver”)
C) Driver.load(“com.mysql.jdbc.Driver”)
D) new com.mysql.jdbc.Driver()
Answer: A
4. Which method of DriverManager class is used to establish a connection to the database?
A) getConnection()
B) connect()
C) createConnection()
D) open()
Answer: A
5. Which JDBC method is used to execute an SQL query?
A) execute()
B) executeQuery()
C) run()
D) executeSQL()
Answer: B
6. Which class is used to execute SQL queries and updates in JDBC?
A) Connection
B) ResultSet
C) Statement
D) PreparedStatement
Answer: C
7. Which method is used to close the Connection object in JDBC?
A) disconnect()
B) close()
C) terminate()
D) end()
Answer: B
EXPERIMENT – 15
Problem definition:Write a java program to demonstrate socket program using Server and Client class in NetBeans 22.
Server Class
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(12345)) { System.out.println(“Server started and waiting for clients…”); Socket socket = serverSocket.accept(); System.out.println(“Client connected.”); // Reading from the client BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = input.readLine(); System.out.println(“Received from client: ” + message); // Responding to the client PrintWriter output = new PrintWriter(socket.getOutputStream(), true); output.println(“Hello, client!”); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } |
Source Program
Client Class
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try (Socket socket = new Socket(“localhost”, 12345)) { // Sending a message to the server PrintWriter output = new PrintWriter(socket.getOutputStream(), true); output.println(“Hello, server!”); // Reading the server’s response BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = input.readLine(); System.out.println(“Received from server: ” + message); } catch (IOException e) { e.printStackTrace(); } } } |
Sample Input / Output
– Server Side
Server started and waiting for clients…
Client connected.
Received from client: Hello, server!
– Client Side
Received from server: Hello, client!
MCQ
- Which class is used to create a server socket in Java?
A) Socket
B) ServerSocket
C) DatagramSocket
D) SocketChannel
Answer: B
- Which method of ServerSocket is used to accept incoming client connections?
A) accept()
B) connect()
C) listen()
D) receive()
Answer: A
- Which class is used to create a client socket in Java?
A) Socket
B) ServerSocket
C) DatagramSocket
D) SocketChannel
Answer: A
- What is the purpose of the getInputStream() method in a socket connection?
A) To obtain a stream to read data from the socket
B) To send data to the socket
C) To close the socket connection
D) To create a new socket connection
Answer: A
- Which method of Socket class is used to send data to the server?
A) getOutputStream()
B) send()
C) write()
D) transfer()
Answer: A
- Which of the following methods is used to close a socket connection?
A) close()
B) disconnect()
C) shutdown()
D) terminate()
Answer: A
- What is the purpose of the BufferedReader class in a socket program?
A) To buffer data before sending it over the network
B) To read data from an input stream efficiently
C) To write data to an output stream efficiently
D) To create a new socket connection
Answer: B
ExercisePrograms
Topic Covered | Problem Definition |
Introduction to JAVA | Write a Java Program to find roots of quadratic equations. |
inheritance | Write a Java program to create a class known as “BankAccount” with methods called deposit() and withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method to prevent withdrawals if the account balance falls below one hundred. |
Abstract Class and Methods | Write a Java Program to create an abstract class named shape that contains two integers and an empty method named printArea. Provide three classes named Rectangle, Triangle and Circle subclass that each one of the classes extends the Class Shape. Each one of the classes contains only the method printArea() that prints the area of Shape. |
Array and Loops | Write a java program to computer the sum of array elements. |
Interface | Write a java program to explain use of interface with any suitable problem. |
Control Structure | Write a java program to find greatest among given three values. |
Loop Structure | Write a java program that implements Selection sort algorithm for sorting a list of numbers in ascending order. |
GUI Interface with Exception Handling | Write a Program that creates User Interface to perform Integer Divisons. The user enters two numbers in text fields, Num1 and Num2.The division of Num1 and Num2 is displayed in the result field when the divide button clicked. If Num1 or Num2 were not integer, the program would throw a NumberFormatException,If Num2 is Zero, and the program would throw an Athematic Exception. Display theException in message box. |
Threads | Write a JAVA program that creates threads by extending Thread class. First thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable) |
Serializations | Write a java program that loads names and phone numbers from the text file where data is organized as one line per record and each field in record are separated by any delimiter. |
Sample LabRecords
The screenshots for JAVA programs using NetBeans are given below. Each experimentmustbewrittenwithproblemdefinition,of thesourceprogram and input/output.
Problem definition: Create an array of integers and print the addition of elements of anarray using java.
Program:
SampleInput/Output
Recommended Reading
Textbook(s)
- Balagurusamy, E. (2019). Programming with Java: A Primer (5th ed.). McGraw-Hill Education.
- Gupta, A. (2018). Java: A Beginner’s Guide (8th ed.). McGraw-Hill Education.
- Patel, S. (2015). Java: The Complete Reference (8th ed.). McGraw-Hill Education.
- Naughton, P., & Schildt, H. (2014). The Complete Reference Java 2 (5th ed.). Tata McGraw-Hill Education.
Reference Book(s)
- Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley Professional.
- Schildt, H. (2018). Java: The Complete Reference (11th ed.). McGraw-Hill Education.
Websites(s)
- (2023, July 17). The Java™ tutorials. Oracle. https://docs.oracle.com/javase/tutorial/https://www.Javatpoint.com/cpp-tutorial
- (2023, January 5). Introduction to Java. GeeksforGeeks. https://www.geeksforgeeks.org/introduction-to-java/
- (n.d.). Java tutorial. W3Schools. https://www.w3schools.com/java/
- Patil, P. (n.d.). Java programming [Online course]. NPTEL. https://nptel.ac.in/courses/106105191/
Lab Manual
Lab Assignment: Introduction to Data Visualization and R Programming
Objective
This lab assignment is designed to introduce you to the basics of data visualization and R programming. By the end of the session, you will understand the importance of data visualization, learn the basics of R and R Studio, and be able to perform fundamental programming tasks in R.
Topics Covered
- Overview of Data Visualization
- Importance of Data Visualization in Data Analysis
- Overview of R and R Studio
- Installation and Setup of the R Environment
- Basic Syntax and Data Types in R
- Variables and Operators
Lab Assignment Tasks
Task 1: Overview of Data Visualization
- Activity: Research and write a brief summary of what data visualization is and why it is crucial in data analysis.
- Solution:
Data Visualization Overview: Data visualization is the graphical representation of information and data. By using visual elements like charts, graphs, and maps, it provides an accessible way to see and understand trends, outliers, and patterns in data. It simplifies complex datasets, enabling stakeholders to make data-driven decisions effectively.
Task 2: Importance of Data Visualization in Data Analysis
- Activity: List three key reasons why data visualization is essential in analyzing data.
- Solution:
- Simplifies Data Understanding: Complex data can be easily interpreted through charts and graphs.
- Enhances Decision Making: Clear visuals support faster and more informed decisions.
- Identifies Trends and Patterns: Visualization helps in spotting trends that might not be apparent in raw data.
Task 3: Overview of R and R Studio
- Activity: Briefly describe what R and R Studio are and their roles in data analysis.
- Solution:
R: R is a programming language designed for statistical computing and data analysis. It provides a variety of tools for statistical modeling, data visualization, and data manipulation. R Studio: R Studio is an integrated development environment (IDE) for R. It makes working with R easier by providing a user-friendly interface, debugging tools, and visualization capabilities.
Task 4: Installation and Setup of the R Environment
- Activity: Follow the steps to install R and R Studio on your system.
- Solution:
- Download R: Visit https://cran.r-project.org/ and download R for your operating system.
- Install R: Run the downloaded installer and follow the setup instructions.
- Download R Studio: Visit https://posit.co/download/rstudio-desktop/ and download the R Studio installer.
- Install R Studio: Run the R Studio installer and follow the setup process.
- Verify Installation: Open R Studio and ensure it connects to the R installation.
Task 5: Basic Syntax and Data Types in R
- Activity: Write R code snippets to demonstrate basic syntax and common data types.
- Solution:
# Basic Syntax
print(“Hello, World!”)
# Data Types
# Numeric
num <- 42
print(num)
# Character
char <- “R Programming”
print(char)
# Logical
logical_val <- TRUE
print(logical_val)
# Vector
vec <- c(1, 2, 3, 4)
print(vec)
Task 6: Variables and Operators in R
- Activity: Create variables and use basic operators in R.
- Solution:
# Variables
x <- 10
y <- 5
# Arithmetic Operators
sum <- x + y
print(sum)
product <- x * y
print(product)
# Relational Operators
is_equal <- x == y
print(is_equal)
# Logical Operators
logical_and <- (x > 5) & (y < 10)
print(logical_and)
Submission Instructions
- Complete the tasks and document your solutions in a text editor or R Markdown.
- Save your R code and output as an R script or Markdown file.
- Submit your file via the course submission platform.
Unit 2 lab Assignment
Lab Assignment: Data Structures in R
Objective:
To understand and practice using various data structures in R such as vectors, lists, matrices, and data frames. Additionally, practice importing and exporting data in R.
Exercise 1: Vectors in R
- Create a numeric vector with the numbers 1 to 10 and print it.
- Create a character vector with the names of five fruits and print it.
- Use a logical condition to create a logical vector indicating whether the numbers in your numeric vector are greater than 5.
Exercise 2: Lists in R
- Create a list containing:
- A numeric vector of numbers 1 to 5.
- A character vector with three city names.
- A logical value TRUE.
- Print the list and access its second element.
Exercise 3: Matrices in R
- Create a 3×3 matrix with numbers 1 to 9 using the matrix() function.
- Rename the rows and columns with appropriate labels (e.g., Row1, Col1).
- Access the element in the second row and third column.
Exercise 4: Data Frames in R
- Create a data frame with the following data:
- Column 1: Student names (“Alice”, “Bob”, “Charlie”)
- Column 2: Marks in Math (85, 90, 78)
- Column 3: Passed status (TRUE, TRUE, FALSE)
- Print the data frame and access the “Marks in Math” column.
- Add a new column “Marks in English” with values 88, 92, 80.
Exercise 5: Importing Data
- Use R’s read.csv() function to import a CSV file (use a sample file such as students.csv with columns Name, Math Marks, and English Marks).
- Print the first few rows using head().
Exercise 6: Exporting Data
- Save the data frame created in Exercise 4 as a CSV file using write.csv().
- Confirm the file was successfully created by re-importing it and printing its contents.
Solution
Exercise 1: Vectors in R
R
Copy code
# Numeric vector
num_vec <- 1:10
print(num_vec)
# Character vector
char_vec <- c(“Apple”, “Banana”, “Cherry”, “Date”, “Elderberry”)
print(char_vec)
# Logical vector
logical_vec <- num_vec > 5
print(logical_vec)
Exercise 2: Lists in R
R
Copy code
# Create a list
my_list <- list(
numbers = 1:5,
cities = c(“New York”, “London”, “Tokyo”),
status = TRUE
)
print(my_list)
# Access the second element
print(my_list$cities)
Exercise 3: Matrices in R
R
Copy code
# Create a matrix
mat <- matrix(1:9, nrow = 3, byrow = TRUE)
rownames(mat) <- c(“Row1”, “Row2”, “Row3”)
colnames(mat) <- c(“Col1”, “Col2”, “Col3”)
print(mat)
# Access element in 2nd row, 3rd column
print(mat[2, 3])
Exercise 4: Data Frames in R
R
Copy code
# Create a data frame
students <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”),
Math_Marks = c(85, 90, 78),
Passed = c(TRUE, TRUE, FALSE)
)
print(students)
# Access the “Math Marks” column
print(students$Math_Marks)
# Add a new column
students$English_Marks <- c(88, 92, 80)
print(students)
Exercise 5: Importing Data
R
Copy code
# Import a CSV file
data <- read.csv(“students.csv”)
print(head(data))
Exercise 6: Exporting Data
R
Copy code
# Export the data frame to a CSV file
write.csv(students, “students_exported.csv”, row.names = FALSE)
# Re-import to verify
exported_data <- read.csv(“students_exported.csv”)
print(exported_data)
Exercise 1: Working with Factors
- Create a character vector containing the categories: “Low”, “Medium”, “High”, “Low”, “High”.
- Convert the character vector into a factor and display its levels.
- Reorder the factor levels to “Low”, “Medium”, “High”.
- Add a new category “Very High” to the factor and verify the new levels.
Exercise 2: Handling Missing Data
- Create a numeric vector with the values: 10, 20, NA, 40, NA, 60.
- Use the is.na() function to identify missing values.
- Replace all NA values with the mean of the non-missing values.
- Verify that there are no more missing values in the vector.
Exercise 3: Data Transformation with dplyr
- Install and load the dplyr package if not already installed.
- Create a data frame with the following columns:
- Name: “Alice”, “Bob”, “Charlie”, “David”, “Eva”
- Age: 25, 30, 35, 40, 45
- Salary: 50000, 55000, 60000, 65000, 70000
- Perform the following transformations using dplyr:
- Filter rows where Salary > 60000.
- Select only the Name and Salary columns.
- Add a new column Tax as 10% of Salary.
- Arrange the data frame by Age in descending order.
Exercise 4: Data Cleaning
- Create a data frame with the following data:
- Product: “A”, “B”, “”, “D”, “E”
- Price: 100, NA, 150, NA, 200
- Quantity: 10, 20, NA, 30, NA
- Clean the data frame by:
- Replacing empty strings in the Product column with “Unknown”.
- Filling missing Price values with the median of the column.
- Dropping rows with missing Quantity values.
- Print the cleaned data frame.
Exercise 5: Manipulating Data Structures
- Create a list with the following elements:
- A numeric vector: c(1, 2, 3, 4, 5)
- A character vector: “Red”, “Green”, “Blue”
- A logical value: TRUE
- Convert the list into a data frame.
- Modify the data frame to add a new column Category with values “A”, “B”, “C”, “D”, “E”.
Solutions
Exercise 1: Working with Factors
R
Copy code
# Create a character vector
categories <- c(“Low”, “Medium”, “High”, “Low”, “High”)
# Convert to factor
categories_factor <- factor(categories)
print(levels(categories_factor))
# Reorder levels
categories_factor <- factor(categories, levels = c(“Low”, “Medium”, “High”))
print(levels(categories_factor))
# Add a new category
categories_factor <- factor(categories_factor, levels = c(“Low”, “Medium”, “High”, “Very High”))
print(levels(categories_factor))
Exercise 2: Handling Missing Data
R
Copy code
# Create a numeric vector
values <- c(10, 20, NA, 40, NA, 60)
# Identify missing values
print(is.na(values))
# Replace NA with mean
values[is.na(values)] <- mean(values, na.rm = TRUE)
print(values)
Exercise 3: Data Transformation with dplyr
R
Copy code
# Install and load dplyr
if (!require(“dplyr”)) install.packages(“dplyr”)
library(dplyr)
# Create data frame
data <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”, “David”, “Eva”),
Age = c(25, 30, 35, 40, 45),
Salary = c(50000, 55000, 60000, 65000, 70000)
)
# Filter rows
filtered_data <- filter(data, Salary > 60000)
print(filtered_data)
# Select columns
selected_data <- select(data, Name, Salary)
print(selected_data)
# Add new column
data <- mutate(data, Tax = Salary * 0.10)
print(data)
# Arrange by Age
arranged_data <- arrange(data, desc(Age))
print(arranged_data)
Exercise 4: Data Cleaning
R
Copy code
# Create data frame
data <- data.frame(
Product = c(“A”, “B”, “”, “D”, “E”),
Price = c(100, NA, 150, NA, 200),
Quantity = c(10, 20, NA, 30, NA)
)
# Replace empty strings
data$Product[data$Product == “”] <- “Unknown”
# Replace missing Price values
data$Price[is.na(data$Price)] <- median(data$Price, na.rm = TRUE)
# Drop rows with missing Quantity
data <- na.omit(data)
print(data)
Exercise 5: Manipulating Data Structures
R
Copy code
# Create a list
my_list <- list(
numbers = c(1, 2, 3, 4, 5),
colors = c(“Red”, “Green”, “Blue”),
status = TRUE
)
# Convert list to data frame
my_data <- as.data.frame(my_list)
print(my_data)
# Add new column
my_data$Category <- c(“A”, “B”, “C”, “D”, “E”)
print(my_data)
This lab covers critical skills in data cleaning and transformation in R, ensuring students get hands-on experience with factors, missing data handling, and manipulating data structures. Let me know if you’d like more exercises or modifications!
UNIT_3_4_
Assignment: Control Structures and Basic Plotting in R
Part 1: Conditional Statements
Task 1:
Write a function check_even_odd() that takes an integer as input and checks if the number is even or odd using an if-else statement. Print “Even” if the number is even and “Odd” if the number is odd.
Solution:
r
Copy code
check_even_odd <- function(num) {
if (num %% 2 == 0) {
print(“Even”)
} else {
print(“Odd”)
}
}
# Test the function
check_even_odd(4) # Output: “Even”
check_even_odd(7) # Output: “Odd”
Task 2:
Write a script that takes an input character and uses the switch statement to return the day of the week based on a numeric input (1 for Monday, 2 for Tuesday, …, 7 for Sunday).
Solution:
r
Copy code
get_day_of_week <- function(day_num) {
switch(day_num,
“1” = “Monday”,
“2” = “Tuesday”,
“3” = “Wednesday”,
“4” = “Thursday”,
“5” = “Friday”,
“6” = “Saturday”,
“7” = “Sunday”,
“Invalid day number”)
}
# Test the function
print(get_day_of_week(3)) # Output: “Wednesday”
print(get_day_of_week(8)) # Output: “Invalid day number”
Part 2: Loops
Task 3:
Write a for loop to print the squares of the first 10 natural numbers (1 to 10).
Solution:
r
Copy code
for (i in 1:10) {
print(i^2)
}
Task 4:
Use a while loop to sum all the even numbers between 1 and 20.
Solution:
r
Copy code
sum_even <- 0
i <- 1
while (i <= 20) {
if (i %% 2 == 0) {
sum_even <- sum_even + i
}
i <- i + 1
}
print(sum_even) # Output: 110
Task 5:
Write a repeat loop that prints numbers from 1 to 5 and exits the loop after printing 5 using the break statement.
Solution:
r
Copy code
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) {
break
}
}
Part 3: Functions
Task 6:
Create a recursive function factorial() that calculates the factorial of a given number.
Solution:
r
Copy code
factorial <- function(n) {
if (n == 1) {
return(1)
} else {
return(n * factorial(n – 1))
}
}
# Test the function
print(factorial(5)) # Output: 120
Task 7:
Define a function fibonacci() that generates the first n numbers in the Fibonacci sequence using a for loop.
Solution:
r
Copy code
fibonacci <- function(n) {
fib_seq <- numeric(n)
fib_seq[1] <- 0
if (n > 1) fib_seq[2] <- 1
for (i in 3:n) {
fib_seq[i] <- fib_seq[i-1] + fib_seq[i-2]
}
return(fib_seq)
}
# Test the function
print(fibonacci(10)) # Output: 0 1 1 2 3 5 8 13 21 34
Part 4: Basic Plotting
Task 8:
Generate a scatter plot of 10 random numbers on the x-axis and their squares on the y-axis. Customize the plot by giving it a title, x-axis label, y-axis label, and changing the point color to red.
Solution:
r
Copy code
set.seed(42)
x <- runif(10, 1, 10) # 10 random numbers between 1 and 10
y <- x^2
plot(x, y, type = “p”, main = “Scatter Plot of x vs x^2”, xlab = “x values”, ylab = “Square of x”, col = “red”)
Task 9:
Create a line plot of the function y = sin(x) for values of x ranging from 0 to 2π. Customize the plot with a title and proper axis labels.
Solution:
r
Copy code
x <- seq(0, 2 * pi, length.out = 100)
y <- sin(x)
plot(x, y, type = “l”, main = “Sine Wave”, xlab = “x (radians)”, ylab = “sin(x)”, col = “blue”)
Task 10:
Create a bar plot of the following data: Categories: “A”, “B”, “C”, “D”, “E” and their respective values: 4, 7, 9, 2, 6. Customize the bar plot with a title, different bar colors, and labels.
Solution:
r
Copy code
categories <- c(“A”, “B”, “C”, “D”, “E”)
values <- c(4, 7, 9, 2, 6)
barplot(values, names.arg = categories, col = rainbow(5), main = “Bar Plot of Categories and Values”, xlab = “Categories”, ylab = “Values”)
Part 5: Bonus Task
Task 11:
Write a function that generates a plot for any mathematical function (e.g., f(x) = x^3, f(x) = log(x)), allowing users to input the function, range of x, and other plot details (title, axis labels).
Solution:
r
Copy code
plot_function <- function(f, x_range, main_title = “Function Plot”, x_label = “x”, y_label = “f(x)”) {
x <- seq(x_range[1], x_range[2], length.out = 100)
y <- sapply(x, f)
plot(x, y, type = “l”, main = main_title, xlab = x_label, ylab = y_label, col = “green”)
}
# Test the function with f(x) = x^3
plot_function(function(x) x^3, c(-5, 5), main_title = “Plot of x^3”, x_label = “x”, y_label = “x^3”)
Instructions for Students:
- Run each code block in R and observe the output.
- Modify the code slightly (e.g., change values, add new conditions) to better understand how control structures and functions work.
- Complete Task 11 for a mathematical function of your choice and submit the output plot with your observations.
Expected Outcome:
Students should understand the use of control structures (conditional statements and loops), how to create and use functions, and how to generate basic plots with customization in R.
This assignment ensures students have hands-on practice with the critical concepts and are able to apply them to real problems.
Unit 4
Lab Assignment 1: Conditional Statements and Loops
Objective:
To develop proficiency in using control structures such as conditional statements and loops in R.
Task 1: Conditional Statements (if-else, switch)
- Write an R script that prompts the user to enter a number and checks whether the number is even or odd using the if-else statement.
R
Copy code
num <- as.integer(readline(prompt=”Enter a number: “))
if (num %% 2 == 0) {
print(“The number is even.”)
} else {
print(“The number is odd.”)
}
- Create a switch statement that takes a number (1 to 7) as input and prints the corresponding day of the week.
R
Copy code
day <- as.integer(readline(prompt=”Enter a number (1 to 7): “))
print(switch(day,
“1” = “Monday”,
“2” = “Tuesday”,
“3” = “Wednesday”,
“4” = “Thursday”,
“5” = “Friday”,
“6” = “Saturday”,
“7” = “Sunday”,
“Invalid input”))
Task 2: Loops (for, while)
- Write a for loop that prints the first 10 numbers in the Fibonacci sequence.
R
Copy code
fib <- numeric(10)
fib[1] <- 0
fib[2] <- 1
for (i in 3:10) {
fib[i] <- fib[i-1] + fib[i-2]
}
print(fib)
- Write a while loop that sums numbers entered by the user until they enter a negative number.
R
Copy code
total <- 0
num <- as.integer(readline(prompt=”Enter a number (negative to stop): “))
while (num >= 0) {
total <- total + num
num <- as.integer(readline(prompt=”Enter another number (negative to stop): “))
}
print(paste(“Total sum is:”, total))
Expected Skills Development:
- Understanding of decision-making in R using if-else and switch.
- Ability to implement and manipulate for and while loops effectively.
Lab Assignment 2: Data Import and Export
Objective:
To gain hands-on experience in reading and writing different data formats in R, and perform basic data preprocessing.
Task 1: Importing and Exporting Data
- Read a CSV file into R and display the first few rows of the data.
R
Copy code
data <- read.csv(“students.csv”)
head(data)
- Clean the data by replacing any missing values with the mean of their respective columns.
R
Copy code
data[is.na(data)] <- mean(data, na.rm=TRUE)
- Write the cleaned data back into a new CSV file.
R
Copy code
write.csv(data, “cleaned_students.csv”, row.names = FALSE)
Task 2: Reading from Excel and Database
- Install and use the readxl package to read an Excel file.
R
Copy code
library(readxl)
data_excel <- read_excel(“students_data.xlsx”)
head(data_excel)
- Use RSQLite to connect to a SQLite database, read data from a table, and display the results.
R
Copy code
library(RSQLite)
conn <- dbConnect(RSQLite::SQLite(), “students.db”)
data_db <- dbGetQuery(conn, “SELECT * FROM students”)
head(data_db)
dbDisconnect(conn)
Expected Skills Development:
- Experience in working with external data files like CSV, Excel, and databases.
- Introduction to basic data preprocessing techniques, including handling missing values.
Lab Assignment 3: Data Visualization with ggplot2
Objective:
To learn the basics of data visualization using the ggplot2 package, focusing on creating meaningful plots for data interpretation.
Task 1: Scatter Plot and Box Plot
- Use the iris dataset to create a scatter plot comparing Sepal.Length and Sepal.Width with color-coded species.
R
Copy code
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
labs(title = “Sepal Length vs Sepal Width”, x = “Sepal Length”, y = “Sepal Width”)
- Create a box plot to visualize the distribution of Petal.Length for each species.
R
Copy code
ggplot(iris, aes(x = Species, y = Petal.Length)) +
geom_boxplot() +
labs(title = “Boxplot of Petal Length by Species”, x = “Species”, y = “Petal Length”)
Task 2: Customization and Themes in ggplot2
- Customize the scatter plot by modifying axis labels, title, and using a custom theme.
R
Copy code
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
labs(title = “Sepal Dimensions”, x = “Length”, y = “Width”) +
theme_minimal()
Expected Skills Development:
- Hands-on experience with ggplot2 for creating scatter plots, box plots, and customizing visualizations.
- Understanding the grammar of graphics and how to modify aesthetics and themes in ggplot2.
Lab Assignment 4: Functions and Recursion
Objective:
To understand how to define and use functions in R, and to explore recursion for solving problems.
Task 1: Defining Functions
- Write a function to calculate the factorial of a number.
R
Copy code
factorial_func <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial_func(n – 1))
}
}
factorial_func(5) # Example call
- Write a function that takes a vector as input and returns the mean and median of the vector.
R
Copy code
stats_func <- function(vec) {
mean_val <- mean(vec)
median_val <- median(vec)
return(list(mean = mean_val, median = median_val))
}
Task 2: Recursive Function
- Create a recursive function to calculate the n-th Fibonacci number.
R
Copy code
fibonacci_func <- function(n) {
if (n <= 1) {
return(n)
} else {
return(fibonacci_func(n – 1) + fibonacci_func(n – 2))
}
}
fibonacci_func(10)
- Compare the performance of this recursive function with an iterative solution.
R
Copy code
fibonacci_iterative <- function(n) {
fib <- numeric(n)
fib[1] <- 0
fib[2] <- 1
for (i in 3:n) {
fib[i] <- fib[i-1] + fib[i-2]
}
return(fib)
}
fibonacci_iterative(10)
Expected Skills Development:
- Mastery in function creation, including handling return values.
- Understanding of recursion and its practical use in solving problems like the Fibonacci sequence.
Unit 5
Lab Assignment 1: Exploring Data Visualization with Base R
Objective:
To practice creating and customizing basic plots using base R graphics.
Tasks:
Task 1: Bar Plot
- Create a dataset with categories and their respective counts.
- Generate a bar plot using the dataset and customize it with titles and colors.
R
Copy code
# Creating the dataset
categories <- c(“A”, “B”, “C”, “D”)
counts <- c(10, 20, 15, 25)
# Creating the bar plot
barplot(counts, names.arg = categories, col = c(“red”, “blue”, “green”, “purple”),
main = “Category Counts”, xlab = “Categories”, ylab = “Counts”)
Task 2: Histogram
- Generate a dataset with random numerical values.
- Create a histogram to visualize the distribution of the dataset.
R
Copy code
# Generating random data
data <- rnorm(100, mean = 50, sd = 10)
# Creating the histogram
hist(data, breaks = 20, col = “lightblue”, main = “Histogram of Random Data”,
xlab = “Values”, ylab = “Frequency”)
Task 3: Pie Chart
- Create a dataset representing proportions.
- Generate a pie chart with labeled slices.
R
Copy code
# Creating the dataset
slices <- c(40, 30, 20, 10)
labels <- c(“Red”, “Blue”, “Green”, “Yellow”)
# Creating the pie chart
pie(slices, labels = labels, main = “Proportions of Colors”, col = c(“red”, “blue”, “green”, “yellow”))
Expected Skills Development:
- Understanding of creating and customizing bar plots, histograms, and pie charts.
- Ability to add titles, labels, and colors to plots for better visualization.
Lab Assignment 2: Data Manipulation with dplyr and tidyr
Objective:
To practice data manipulation and tidying using dplyr and tidyr packages.
Tasks:
Task 1: Data Manipulation Using dplyr
- Create a sample dataset with multiple columns.
- Apply dplyr functions to filter, select, and summarize the data.
R
Copy code
library(dplyr)
# Sample dataset
data <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”, “David”),
Age = c(23, 45, 35, 30),
Salary = c(50000, 60000, 55000, 52000)
)
# Filter data for Age > 30
filtered_data <- data %>% filter(Age > 30)
# Select Name and Salary columns
selected_data <- data %>% select(Name, Salary)
# Add a new column “Bonus”
data_with_bonus <- data %>% mutate(Bonus = Salary * 0.10)
# Calculate average Salary
avg_salary <- data %>% summarize(AverageSalary = mean(Salary))
print(filtered_data)
print(selected_data)
print(data_with_bonus)
print(avg_salary)
Task 2: Data Tidying Using tidyr
- Create a wide-format dataset.
- Convert the wide-format dataset to long-format and vice versa using tidyr functions.
R
Copy code
library(tidyr)
# Wide-format dataset
wide_data <- data.frame(
Name = c(“Alice”, “Bob”),
Math = c(90, 80),
Science = c(85, 88)
)
# Convert to long-format
long_data <- wide_data %>% gather(Subject, Score, Math:Science)
print(long_data)
# Convert back to wide-format
wide_data_back <- long_data %>% spread(Subject, Score)
print(wide_data_back)
Expected Skills Development:
- Proficiency in data filtering, selection, and summary using dplyr.
- Ability to reshape data using tidyr for better data organization.
Lab Assignment 3: Advanced Data Visualization with ggplot2
Objective:
To practice creating and customizing advanced plots using the ggplot2 package.
Tasks:
Task 1: Scatter Plot with ggplot2
- Use the built-in mtcars dataset.
- Create a scatter plot showing the relationship between wt (weight) and mpg (miles per gallon), and color-code by cyl (number of cylinders).
R
Copy code
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = “Car Weight vs. MPG”, x = “Weight”, y = “Miles Per Gallon”) +
scale_color_discrete(name = “Cylinders”) +
theme_minimal()
Task 2: Box Plot with ggplot2
- Create a box plot to show the distribution of mpg by cyl.
R
Copy code
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot(fill = “lightblue”) +
labs(title = “Box Plot of MPG by Number of Cylinders”, x = “Number of Cylinders”, y = “Miles Per Gallon”) +
theme_minimal()
Task 3: Customizing ggplot2
- Create a scatter plot with a regression line and custom themes.
R
Copy code
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(aes(color = factor(cyl)), size = 3) +
geom_smooth(method = “lm”, se = FALSE, color = “black”) +
labs(title = “Car Weight vs. MPG with Regression Line”, x = “Weight”, y = “Miles Per Gallon”) +
theme_light() +
theme(legend.position = “bottom”)
Expected Skills Development:
- Ability to create and customize scatter plots and box plots using ggplot2.
- Skills in adding regression lines, customizing themes, and modifying aesthetics.
Lab Assignment 4: Functions and Recursion in R
Objective:
To develop skills in defining and using functions, including recursive functions in R.
Tasks:
Task 1: Function Definition and Usage
- Define a function to calculate the factorial of a number.
- Use the function to compute the factorial of 5.
R
Copy code
# Defining the factorial function
factorial_func <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial_func(n – 1))
}
}
# Using the function
factorial_of_5 <- factorial_func(5)
print(factorial_of_5)
Task 2: Function with Multiple Outputs
- Define a function that takes a vector and returns the mean and median.
- Apply the function to a sample vector.
R
Copy code
# Defining the function
stats_func <- function(vec) {
mean_val <- mean(vec)
median_val <- median(vec)
return(list(mean = mean_val, median = median_val))
}
# Using the function
sample_vector <- c(10, 20, 30, 40, 50)
stats_result <- stats_func(sample_vector)
print(stats_result)
Task 3: Recursive Function Example
- Write a recursive function to compute the Fibonacci sequence.
- Compare the results with an iterative function.
R
Copy code
# Recursive Fibonacci function
fibonacci_recursive <- function(n) {
if (n <= 1) {
return(n)
} else {
return(fibonacci_recursive(n – 1) + fibonacci_recursive(n – 2))
}
}
# Iterative Fibonacci function
fibonacci_iterative <- function(n) {
fib <- numeric(n)
fib[1] <- 0
fib[2] <- 1
for (i in 3:n) {
fib[i] <- fib[i-1] + fib[i-2]
}
return(fib)
}
# Using the functions
print(fibonacci_recursive(10))
print(fibonacci_iterative(10))
Expected Skills Development:
- Mastery in defining and using functions for various calculations.
- Understanding of recursion and its application in solving problems like the Fibonacci sequence.
Unit 6
Professional Lab Assignment: Advanced Data Visualization with ggplot2
Objective:
To enhance your skills in data visualization using the ggplot2 package in R. You will create various types of plots, customize their appearance, and perform statistical data visualizations.
Part 1: Overview of ggplot2 Package
Task: Install and load the ggplot2 package. Familiarize yourself with its core components: data, aesthetics, geometries, and themes.
Instructions:
- Install and Load ggplot2:
R
Copy code
install.packages(“ggplot2”)
library(ggplot2)
- Familiarize Yourself with the ggplot2 Components:
- Data: The dataset you will use.
- Aesthetics: How data variables are mapped to visual properties (e.g., aes(x = var1, y = var2)).
- Geometries: Different types of plots (e.g., geom_point(), geom_line()).
- Themes: Customization options (e.g., theme_minimal()).
Part 2: Creating Basic Plots
Task: Create scatter plots, line graphs, and boxplots using the mtcars dataset.
Instructions:
- Scatter Plot:
Explanation: A scatter plot visualizes the relationship between two continuous variables. You will map the wt (weight) to the x-axis and mpg (miles per gallon) to the y-axis, and use different colors for different numbers of cylinders.
Example:
R
Copy code
# Scatter Plot with ggplot2
scatter_plot <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = “Scatter Plot of Weight vs. MPG”,
x = “Weight”,
y = “Miles Per Gallon”,
color = “Number of Cylinders”) +
theme_minimal()
print(scatter_plot)
- Line Graph:
Explanation: A line graph shows trends over time or another continuous variable. Here, you will plot mpg as a function of wt.
Example:
R
Copy code
# Line Graph with ggplot2
line_graph <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_line(color = “blue”, size = 1) +
geom_point(size = 3, color = “red”) +
labs(title = “Line Graph of MPG Over Weight”,
x = “Weight”,
y = “Miles Per Gallon”) +
theme_classic()
print(line_graph)
- Boxplot:
Explanation: A boxplot provides a summary of one or more continuous variables by showing their distribution. In this case, you’ll visualize the distribution of mpg by the number of gears (gear).
Example:
R
Copy code
# Boxplot with ggplot2
boxplot <- ggplot(mtcars, aes(x = factor(gear), y = mpg)) +
geom_boxplot(fill = “lightblue”) +
labs(title = “Boxplot of MPG by Number of Gears”,
x = “Number of Gears”,
y = “Miles Per Gallon”) +
theme_bw()
print(boxplot)
Part 3: Customizing Plots
Task: Customize your plots with different themes, labels, and colors.
Instructions:
- Customize the Scatter Plot:
Explanation: Adjust the appearance of your scatter plot by changing the theme, axis labels, and point colors.
Example:
R
Copy code
# Customized Scatter Plot
custom_scatter_plot <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = “Customized Scatter Plot of Weight vs. MPG”,
x = “Weight”,
y = “Miles Per Gallon”,
color = “Number of Cylinders”) +
theme(
plot.title = element_text(hjust = 0.5, color = “blue”, size = 14),
axis.title.x = element_text(color = “red”, size = 12),
axis.title.y = element_text(color = “red”, size = 12),
panel.background = element_rect(fill = “lightgray”)
)
print(custom_scatter_plot)
- Customize the Line Graph:
Explanation: Add a custom theme and adjust the colors for better visualization.
Example:
R
Copy code
# Customized Line Graph
custom_line_graph <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_line(color = “darkgreen”, size = 1.2) +
geom_point(size = 4, color = “orange”) +
labs(title = “Customized Line Graph of MPG Over Weight”,
x = “Weight”,
y = “Miles Per Gallon”) +
theme_minimal() +
scale_color_manual(values = c(“darkgreen”, “orange”))
print(custom_line_graph)
Part 4: Statistical Data Visualization
Task: Use ggplot2 to visualize statistical summaries, distributions, and correlations.
Instructions:
- Visualize Distribution:
Explanation: Use a histogram to display the distribution of mpg.
Example:
R
Copy code
# Histogram of MPG
histogram <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 10, fill = “skyblue”, color = “black”) +
labs(title = “Histogram of MPG”,
x = “Miles Per Gallon”,
y = “Frequency”) +
theme_minimal()
print(histogram)
- Add Regression Line:
Explanation: Add a regression line to a scatter plot to show the trend.
Example:
R
Copy code
# Scatter Plot with Regression Line
scatter_with_regression <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = “lm”, se = FALSE, color = “red”) +
labs(title = “Scatter Plot with Regression Line”,
x = “Weight”,
y = “Miles Per Gallon”) +
theme_light()
print(scatter_with_regression)
- Visualize Correlations:
Explanation: Create a plot to show correlations between wt and mpg.
Example:
R
Copy code
# Correlation Plot with ggplot2
correlation_plot <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
stat_cor(method = “pearson”) + # Pearson correlation coefficient
labs(title = “Correlation Plot of Weight and MPG”,
x = “Weight”,
y = “Miles Per Gallon”,
color = “Number of Cylinders”) +
theme_minimal()
print(correlation_plot)
Deliverables:
- Submit an R script (.R file) containing all the code and plots for each part of the assignment.
- Include comments in your code explaining the purpose and customization of each plot.
Evaluation Criteria:
- Correct use of ggplot2 functions and components.
- Ability to customize plots effectively.
- Clarity and readability of the visualizations.
- Proper documentation and comments in the code.
Unit 7
- Visualizing Distributions
Task: Density Plots and Violin Plots
- Density Plot:
- Description: Create a density plot to visualize the distribution of a chosen continuous variable from the mtcars dataset.
- Instructions:
- Load the mtcars dataset.
- Use ggplot2 to create a density plot for the mpg (miles per gallon) variable.
- Customize the plot by adding labels and adjusting the fill color.
- Example Code:
R
Copy code
library(ggplot2)
data(mtcars)
# Density Plot
density_plot <- ggplot(mtcars, aes(x = mpg)) +
geom_density(fill = “skyblue”, alpha = 0.5) +
labs(title = “Density Plot of MPG”,
x = “Miles Per Gallon”,
y = “Density”) +
theme_minimal()
print(density_plot)
- Violin Plot:
- Description: Create a violin plot to show the distribution of mpg across different gear categories.
- Instructions:
- Use the mtcars dataset.
- Create a violin plot with gear on the x-axis and mpg on the y-axis.
- Customize the plot with colors and labels.
- Example Code:
R
Copy code
# Violin Plot
violin_plot <- ggplot(mtcars, aes(x = factor(gear), y = mpg)) +
geom_violin(fill = “lightgreen”, alpha = 0.6) +
labs(title = “Violin Plot of MPG by Number of Gears”,
x = “Number of Gears”,
y = “Miles Per Gallon”) +
theme_classic()
print(violin_plot)
- Plotting Regression Models and Diagnostics
Task: Linear Regression and Residual Plots
- Regression Model:
- Description: Fit a linear regression model to the mtcars dataset and plot the regression line.
- Instructions:
- Fit a linear model with wt (weight) as the predictor and mpg as the response variable.
- Plot the regression line on a scatter plot.
- Example Code:
R
Copy code
# Fit the Linear Model
model <- lm(mpg ~ wt, data = mtcars)
# Scatter Plot with Regression Line
regression_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = “lm”, se = FALSE, color = “red”) +
labs(title = “Regression Line for Weight vs. MPG”,
x = “Weight”,
y = “Miles Per Gallon”) +
theme_minimal()
print(regression_plot)
- Residual Plot:
- Description: Create a residual plot to evaluate the fit of the regression model.
- Instructions:
- Extract residuals from the linear model.
- Plot residuals against fitted values.
- Example Code:
R
Copy code
# Residual Plot
residuals_plot <- ggplot(model, aes(x = .fitted, y = .resid)) +
geom_point() +
labs(title = “Residual Plot”,
x = “Fitted Values”,
y = “Residuals”) +
theme_minimal()
print(residuals_plot)
- Creating Correlation Matrices and Heatmaps
Task: Correlation Matrix and Heatmap
- Correlation Matrix:
- Description: Compute and plot the correlation matrix for a subset of numeric variables from the mtcars dataset.
- Instructions:
- Calculate the correlation matrix for the mtcars dataset.
- Use the corrplot package to visualize the correlation matrix.
- Example Code:
R
Copy code
library(corrplot)
# Compute Correlation Matrix
cor_matrix <- cor(mtcars)
# Plot Correlation Matrix
corrplot(cor_matrix, method = “color”, tl.cex = 0.7, addCoef.col = “black”)
- Heatmap:
- Description: Create a heatmap to visualize the correlation matrix using ggplot2.
- Instructions:
- Melt the correlation matrix into a long format.
- Plot the heatmap using ggplot2.
- Example Code:
R
Copy code
library(reshape2)
library(ggplot2)
# Melt the Correlation Matrix
cor_matrix_melted <- melt(cor_matrix)
# Heatmap
heatmap_plot <- ggplot(cor_matrix_melted, aes(Var1, Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(low = “blue”, mid = “white”, high = “red”, midpoint = 0) +
labs(title = “Heatmap of Correlations”,
x = “”,
y = “”) +
theme_minimal()
print(heatmap_plot)
- Interactive Visualizations with Plotly and Shiny
Task: Interactive Plots and Shiny App
- Interactive Plot with Plotly:
- Description: Create an interactive scatter plot using the plotly package.
- Instructions:
- Use the mtcars dataset.
- Create an interactive scatter plot with plotly.
- Example Code:
R
Copy code
library(plotly)
# Create Interactive Plot
interactive_plot <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = “Interactive Scatter Plot of Weight vs. MPG”,
x = “Weight”,
y = “Miles Per Gallon”,
color = “Number of Cylinders”)
# Convert ggplot to Plotly
ggplotly(interactive_plot)
- Basic Shiny App:
- Description: Develop a simple Shiny app that allows users to filter data and visualize a scatter plot.
- Instructions:
- Create a Shiny app with a slider input to filter the range of wt values.
- Display an interactive scatter plot based on the filtered data.
- Example Code:
R
Copy code
library(shiny)
library(ggplot2)
# Define UI
ui <- fluidPage(
titlePanel(“Shiny Scatter Plot”),
sidebarLayout(
sidebarPanel(
sliderInput(“slider”, “Select Weight Range:”,
min = min(mtcars$wt), max = max(mtcars$wt), value = c(min(mtcars$wt), max(mtcars$wt)))
),
mainPanel(
plotOutput(“scatterPlot”)
)
)
)
# Define Server Logic
server <- function(input, output) {
output$scatterPlot <- renderPlot({
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
xlim(input$slider) +
labs(title = “Scatter Plot of Weight vs. MPG”,
x = “Weight”,
y = “Miles Per Gallon”)
})
}
# Run the App
shinyApp(ui = ui, server = server)
Submission Instructions:
- Complete each task by running the provided code snippets and adapting them as needed.
- Save your scripts and outputs as R scripts (.R files) or R Markdown documents (.Rmd files).
- Submit your completed assignment through the course’s learning management system by the deadline provided.
Unit 8
Practical Lab Assignment: Interactive and Time Series Data Visualization
Objective: Develop skills in interactive data visualization using plotly and shiny, and perform time series analysis to understand trends and seasonality.
Part 1: Interactive Data Visualization
1.1 Interactive Plot with Plotly
Task: Create an interactive scatter plot using the plotly package. The plot should display the relationship between wt (weight) and mpg (miles per gallon) from the mtcars dataset. Differentiate the points by the number of cylinders (cyl).
Instructions:
- Load the necessary libraries and dataset.
- Create a scatter plot with interactive features using plotly.
- Customize the plot with appropriate titles, axis labels, and legends.
Example Code:
r
Copy code
library(plotly)
data(mtcars)
# Create Interactive Scatter Plot
interactive_plot <- plot_ly(mtcars, x = ~wt, y = ~mpg, color = ~factor(cyl),
type = ‘scatter’, mode = ‘markers’,
text = ~paste(“Model:”, rownames(mtcars))) %>%
layout(title = “Interactive Scatter Plot of Weight vs. MPG”,
xaxis = list(title = “Weight”),
yaxis = list(title = “Miles Per Gallon”))
interactive_plot
1.2 Interactive Dashboard with Shiny
Task: Build an interactive dashboard using the shiny package to allow users to explore a subset of the mtcars dataset. Provide a slider to select the number of observations and display a scatter plot of wt vs. mpg.
Instructions:
- Define the UI with a slider input and plot output.
- Define the server function to render the scatter plot based on slider input.
- Run the Shiny app.
Example Code:
r
Copy code
library(shiny)
# Define UI
ui <- fluidPage(
titlePanel(“Interactive Dashboard with Shiny”),
sidebarLayout(
sidebarPanel(
sliderInput(“num”, “Number of Observations:”, min = 1, max = nrow(mtcars), value = 10)
),
mainPanel(
plotOutput(“scatterPlot”)
)
)
)
# Define Server
server <- function(input, output) {
output$scatterPlot <- renderPlot({
data <- mtcars[1:input$num, ]
plot(data$wt, data$mpg, main = “Weight vs. MPG”,
xlab = “Weight”, ylab = “Miles Per Gallon”,
pch = 19, col = data$cyl)
})
}
# Run App
shinyApp(ui = ui, server = server)
Part 2: Time Series Visualization
2.1 Plotting Time Series Data
Task: Plot a time series line graph of monthly data. Use the following sample data representing a hypothetical monthly sales figure.
Instructions:
- Create a time series object using the sample data.
- Plot the time series data using ggplot2.
Example Code:
r
Copy code
library(ggplot2)
# Sample Time Series Data
data <- data.frame(
Date = seq(as.Date(‘2023-01-01’), by = ‘month’, length.out = 12),
Sales = c(200, 220, 250, 270, 290, 310, 330, 350, 370, 390, 410, 430)
)
# Time Series Plot
ggplot(data, aes(x = Date, y = Sales)) +
geom_line(color = “blue”) +
labs(title = “Monthly Sales Over a Year”,
x = “Date”,
y = “Sales”) +
theme_minimal()
2.2 Understanding Trends and Seasonality
Task: Perform seasonal decomposition on the time series data and plot the decomposed components: trend, seasonality, and residuals.
Instructions:
- Create a time series object with a frequency that represents seasonality (e.g., monthly data with yearly seasonality).
- Use the decompose function to perform seasonal decomposition.
- Plot the decomposed components.
Example Code:
r
Copy code
library(forecast)
# Convert Data to Time Series Object
ts_data <- ts(data$Sales, frequency = 12, start = c(2023, 1))
# Decompose Time Series
decomp <- decompose(ts_data)
# Plot Decomposition
plot(decomp)
Submission Instructions
- Code: Submit R scripts containing the code for each task.
- Plots: Ensure that all plots are correctly labeled and annotated.
- Documentation: Include comments in the code to explain each step and its purpose.
- Results: Provide a brief summary of the insights gained from the visualizations.
Lab assignment 9
Detailed Lab Assignment: Data Manipulation with dplyr and tidyr
Objective:
This lab assignment focuses on using the dplyr and tidyr packages to efficiently manipulate and summarize data. By completing these exercises, you will gain practical skills in filtering, selecting, mutating, and summarizing data with grouping.
Lab Assignment: Data Manipulation with dplyr, tidyr, and Geospatial Data in R
Introduction to dplyr
Problem 1:
Use the built-in `mtcars` dataset to filter cars with a mileage (`mpg`) greater than 20 and 4 cylinders (`cyl`).
Solution:
library(dplyr)
filtered_cars <- mtcars %>% filter(mpg > 20, cyl == 4)
filtered_cars
Explanation:
The `filter()` function subsets rows based on specified conditions. Here, cars with `mpg` > 20 and `cyl` == 4 are selected.
Problem 2:
From the `mtcars` dataset, extract only the columns `mpg`, `cyl`, and `hp`.
Solution:
selected_columns <- mtcars %>% select(mpg, cyl, hp)
selected_columns
Explanation:
The `select()` function extracts specific columns from a dataset. Only `mpg`, `cyl`, and `hp` are selected.
Problem 3:
Add a new column `power_to_weight` to the `mtcars` dataset by dividing `hp` by `wt`.
Solution:
mutated_data <- mtcars %>% mutate(power_to_weight = hp / wt)
mutated_data
Explanation:
The `mutate()` function creates new columns or modifies existing ones. Here, a new column `power_to_weight` is added.
Summarizing Data with group_by and summarize
Problem 1:
Find the average `mpg` for each cylinder count in the `mtcars` dataset.
Solution:
avg_mpg <- mtcars %>%
group_by(cyl) %>%
summarize(avg_mpg = mean(mpg))
avg_mpg
Explanation:
The `group_by()` function groups data by a column, and `summarize()` computes the summary statistic (mean here) for each group.
Reshaping Data with tidyr
Problem 1:
Convert the `mtcars` dataset to long format for the columns `mpg`, `hp`, and `wt`.
Solution:
library(tidyr)
long_format <- mtcars %>%
select(mpg, hp, wt) %>%
gather(key = “metric”, value = “value”)
long_format
Explanation:
The `gather()` function reshapes data from wide to long format by combining columns into key-value pairs.
Handling Geospatial Data
Problem 1:
Using the `ggmap` package, plot the locations of New York, London, and Tokyo on a world map.
Solution:
library(ggmap)
locations <- data.frame(
city = c(“New York”, “London”, “Tokyo”),
lat = c(40.7128, 51.5074, 35.6895),
lon = c(-74.0060, -0.1278, 139.6917)
)
world_map <- get_map(location = “world”, zoom = 1)
ggmap(world_map) +
geom_point(data = locations, aes(x = lon, y = lat), color = “red”, size = 3)
Explanation:
The `ggmap()` function plots a map, and `geom_point()` adds specific points for the given locations.
:Python
Exercise 1: Filtering Data
- Create a data frame with the following data:
- Name: “Alice”, “Bob”, “Charlie”, “David”, “Eva”
- Age: 25, 30, 35, 40, 45
- Salary: 50000, 60000, 55000, 70000, 65000
- Filter the rows where Age > 30 and print the result.
- Filter the rows where Salary >= 60000 and Age <= 40.
Exercise 2: Selecting Columns
- Use the same data frame from Exercise 1.
- Select only the Name and Salary columns.
- Select all columns except Age.
Exercise 3: Adding New Columns with mutate
- Use the same data frame.
- Add a new column Bonus as 10% of Salary.
- Create another column Total Income as the sum of Salary and Bonus.
Exercise 4: Summarizing Data with summarize
- Use the same data frame.
- Calculate the average Salary of all employees.
- Find the total Salary paid to all employees.
Exercise 5: Grouping and Summarizing Data with group_by
- Create a new data frame with the following data:
- Department: “HR”, “IT”, “HR”, “IT”, “Finance”
- Employee: “Alice”, “Bob”, “Charlie”, “David”, “Eva”
- Salary: 50000, 60000, 55000, 70000, 65000
- Group the data by Department and calculate:
- The average Salary in each department.
- The total Salary in each department.
Exercise 6: Tidying Data with tidyr
- Create a data frame with the following data:
- Name: “Alice”, “Bob”, “Charlie”
- Year1: 85, 90, 78
- Year2: 88, 92, 80
- Year3: 91, 85, 82
- Use the pivot_longer() function to transform the data into long format, where each row represents a Name, Year, and Score.
- Use the pivot_wider() function to revert the data back to its original format.
Solutions
Exercise 1: Filtering Data
R
Copy code
library(dplyr)
# Create data frame
data <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”, “David”, “Eva”),
Age = c(25, 30, 35, 40, 45),
Salary = c(50000, 60000, 55000, 70000, 65000)
)
# Filter rows where Age > 30
filtered_data1 <- filter(data, Age > 30)
print(filtered_data1)
# Filter rows where Salary >= 60000 and Age <= 40
filtered_data2 <- filter(data, Salary >= 60000, Age <= 40)
print(filtered_data2)
Exercise 2: Selecting Columns
R
Copy code
# Select only Name and Salary columns
selected_columns1 <- select(data, Name, Salary)
print(selected_columns1)
# Select all columns except Age
selected_columns2 <- select(data, -Age)
print(selected_columns2)
Exercise 3: Adding New Columns with mutate
R
Copy code
# Add Bonus column
data <- mutate(data, Bonus = Salary * 0.10)
print(data)
# Add Total Income column
data <- mutate(data, Total_Income = Salary + Bonus)
print(data)
Exercise 4: Summarizing Data with summarize
R
Copy code
# Calculate average Salary
average_salary <- summarize(data, Average_Salary = mean(Salary))
print(average_salary)
# Calculate total Salary
total_salary <- summarize(data, Total_Salary = sum(Salary))
print(total_salary)
Exercise 5: Grouping and Summarizing Data with group_by
R
Copy code
# Create new data frame
department_data <- data.frame(
Department = c(“HR”, “IT”, “HR”, “IT”, “Finance”),
Employee = c(“Alice”, “Bob”, “Charlie”, “David”, “Eva”),
Salary = c(50000, 60000, 55000, 70000, 65000)
)
# Group by Department and calculate average Salary
avg_salary_by_dept <- department_data %>%
group_by(Department) %>%
summarize(Average_Salary = mean(Salary))
print(avg_salary_by_dept)
# Group by Department and calculate total Salary
total_salary_by_dept <- department_data %>%
group_by(Department) %>%
summarize(Total_Salary = sum(Salary))
print(total_salary_by_dept)
Exercise 6: Tidying Data with tidyr
R
Copy code
library(tidyr)
# Create data frame
scores <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”),
Year1 = c(85, 90, 78),
Year2 = c(88, 92, 80),
Year3 = c(91, 85, 82)
)
# Transform to long format
long_format <- pivot_longer(scores, cols = starts_with(“Year”),
names_to = “Year”, values_to = “Score”)
print(long_format)
# Revert to wide format
wide_format <- pivot_wider(long_format, names_from = Year, values_from = Score)
print(wide_format)
This lab assignment covers essential data manipulation techniques using dplyr and tidyr. By practicing these exercises, you will develop proficiency in filtering, summarizing, grouping, and tidying data. Let me know if you’d like additional exercises or explanations!
Exercise 7: Filtering with Multiple Conditions
- Use the data frame from Exercise 1.
- Filter the rows where:
- Age is between 30 and 40 (inclusive).
- Salary is not equal to 60000.
Exercise 8: Conditional Mutations
- Use the data frame from Exercise 1.
- Add a new column Performance where:
- “Excellent” if Salary > 60000.
- “Good” if Salary is between 50000 and 60000.
- “Needs Improvement” otherwise.
Exercise 9: Sorting Data with arrange
- Sort the data frame by Salary in descending order.
- Sort the data frame first by Age (ascending) and then by Salary (descending).
Exercise 10: Combining Grouping and Filtering
- Use the data frame from Exercise 5 (department_data).
- Group by Department and calculate the total Salary.
- Filter out groups where the total Salary is less than 120,000.
Exercise 11: Using case_when for Complex Conditions
- Use the data frame from Exercise 1.
- Add a new column Tax Bracket where:
- “Low” if Salary < 55000.
- “Medium” if Salary is between 55000 and 65000.
- “High” if Salary > 65000.
Exercise 12: Tidying with Nested Data
- Create the following data frame:
- Country: “USA”, “Canada”, “Mexico”
- Year2019: 300, 250, 200
- Year2020: 350, 300, 220
- Year2021: 400, 350, 240
- Transform the data into long format using pivot_longer().
- Add a new column Growth Rate to calculate the percentage change between Year2019 and Year2021.
Exercise 13: Reshaping Data with Multiple Keys
- Create the following data frame:
- Student: “Alice”, “Bob”, “Charlie”
- Math_Sem1: 80, 90, 85
- Math_Sem2: 85, 92, 88
- Science_Sem1: 78, 88, 80
- Science_Sem2: 82, 90, 84
- Use pivot_longer() to create a long format with columns:
- Student, Subject, Semester, and Score.
- Use pivot_wider() to restore the original wide format.
Exercise 14: Joining Data Frames
- Create two data frames:
- students:
- ID: 1, 2, 3
- Name: “Alice”, “Bob”, “Charlie”
- Department: “HR”, “IT”, “Finance”
- scores:
- ID: 1, 2, 4
- Math: 85, 90, 78
- English: 88, 92, 80
- students:
- Perform the following joins:
- Inner join to match only rows with IDs present in both tables.
- Left join to include all rows from students.
- Full join to include all rows from both tables.
Exercise 15: Replacing Missing Data
- Use the data frame from Exercise 4 (data with Product, Price, and Quantity).
- Replace missing Quantity values with the median of the column.
- Replace missing Price values with the string “Unavailable”.
Exercise 16: Chaining with %>%
- Use the data frame from Exercise 1.
- Perform the following transformations in a single chain:
- Filter rows where Age > 30.
- Select Name and Salary columns.
- Add a new column Annual Bonus as 15% of Salary.
- Arrange rows by Salary in descending order.
Exercise 17: Splitting and Combining Columns
- Create a data frame with a single column Full Name containing: “Alice Johnson”, “Bob Smith”, “Charlie Brown”.
- Split the Full Name column into First Name and Last Name using separate().
- Combine First Name and Last Name back into a single column using unite().
Exercise 18: Removing Duplicates
- Create a data frame with the following data:
- ID: 1, 2, 2, 3, 4, 4
- Name: “Alice”, “Bob”, “Bob”, “Charlie”, “David”, “David”
- Remove duplicate rows based on ID using distinct().
Exercise 19: Wide-to-Long Transformation for Multiple Variables
- Create the following data frame:
- Store: “A”, “B”, “C”
- Sales_Q1: 100, 200, 300
- Sales_Q2: 150, 250, 350
- Profit_Q1: 50, 100, 150
- Profit_Q2: 75, 125, 175
- Use pivot_longer() to transform the data into long format with Metric (Sales or Profit) and Quarter.
Exercise 20: Case Study – Real-Life Data Transformation
- Download a sample dataset (e.g., mtcars or iris) in R.
- Perform the following tasks:
- Filter rows where mpg > 20.
- Group by cyl (cylinders) and calculate the average hp (horsepower) for each group.
- Add a new column Efficiency by dividing mpg by hp.
- Arrange the rows by Efficiency in descending order.
Let me know which examples you’d like detailed solutions for or additional exercises! 😊
You said:
solution above exercise
ChatGPT said:
ChatGPT
Solutions to Additional Exercises
Below are the detailed solutions to the exercises provided:
Solution 7: Filtering with Multiple Conditions
RCopy code# Use data from Exercise 1filtered_data <- filter(data, Age >=30& Age <=40, Salary !=60000)print(filtered_data)
Solution 8: Conditional Mutations
RCopy code# Add Performance columndata <- mutate(data, Performance = case_when( Salary >60000~”Excellent”, Salary >=50000& Salary <=60000~”Good”,TRUE~”Needs Improvement”))print(data)
Solution 9: Sorting Data with arrange
RCopy code# Sort by Salary in descending ordersorted_data1 <- arrange(data, desc(Salary))print(sorted_data1) # Sort by Age ascending and Salary descendingsorted_data2 <- arrange(data, Age, desc(Salary))print(sorted_data2)
Solution 10: Combining Grouping and Filtering
RCopy code# Group by Department and calculate total Salarygrouped_data <- department_data %>% group_by(Department)%>% summarize(Total_Salary =sum(Salary))%>% filter(Total_Salary >=120000)print(grouped_data)
Solution 11: Using case_when for Complex Conditions
RCopy code# Add Tax Bracket columndata <- mutate(data, Tax_Bracket = case_when( Salary <55000~”Low”, Salary >=55000& Salary <=65000~”Medium”, Salary >65000~”High”))print(data)
Solution 12: Tidying with Nested Data
RCopy code# Create the data framecountry_data <- data.frame( Country =c(“USA”,”Canada”,”Mexico”), Year2019 =c(300,250,200), Year2020 =c(350,300,220), Year2021 =c(400,350,240)) # Transform into long formatlong_data <- pivot_longer(country_data, cols = starts_with(“Year”), names_to =”Year”, values_to =”Value”)print(long_data) # Calculate growth rategrowth_rate <- long_data %>% filter(Year %in%c(“Year2019″,”Year2021″))%>% group_by(Country)%>% summarize(Growth_Rate =(Value[Year ==”Year2021″]- Value[Year ==”Year2019″])/ Value[Year ==”Year2019”]*100)print(growth_rate)
Solution 13: Reshaping Data with Multiple Keys
RCopy code# Create the data framesubject_data <- data.frame( Student =c(“Alice”,”Bob”,”Charlie”), Math_Sem1 =c(80,90,85), Math_Sem2 =c(85,92,88), Science_Sem1 =c(78,88,80), Science_Sem2 =c(82,90,84)) # Long formatlong_subject_data <- pivot_longer(subject_data, cols =-Student, names_to =c(“Subject”,”Semester”), names_sep =”_”)print(long_subject_data) # Wide formatwide_subject_data <- pivot_wider(long_subject_data, names_from =c(Subject, Semester), values_from = value)print(wide_subject_data)
Solution 14: Joining Data Frames
RCopy code# Create data framesstudents <- data.frame( ID =c(1,2,3), Name =c(“Alice”,”Bob”,”Charlie”), Department =c(“HR”,”IT”,”Finance”)) scores <- data.frame( ID =c(1,2,4), Math =c(85,90,78), English =c(88,92,80)) # Inner joininner_joined <- inner_join(students, scores, by =”ID”)print(inner_joined) # Left joinleft_joined <- left_join(students, scores, by =”ID”)print(left_joined) # Full joinfull_joined <- full_join(students, scores, by =”ID”)print(full_joined)
Solution 15: Replacing Missing Data
RCopy code# Replace missing Quantity values with mediandata$Quantity[is.na(data$Quantity)]<- median(data$Quantity, na.rm =TRUE) # Replace missing Price values with “Unavailable”data$Price[is.na(data$Price)]<-“Unavailable”print(data)
Solution 16: Chaining with %>%
RCopy code# Perform transformations with pipingresult <- data %>% filter(Age >30)%>% select(Name, Salary)%>% mutate(Annual_Bonus = Salary *0.15)%>% arrange(desc(Salary))print(result)
Solution 17: Splitting and Combining Columns
RCopy code# Create the data framenames_data <- data.frame(Full_Name =c(“Alice Johnson”,”Bob Smith”,”Charlie Brown”)) # Split Full_Namesplit_names <- separate(names_data, Full_Name, into =c(“First_Name”,”Last_Name”), sep =” “)print(split_names) # Combine backcombined_names <- unite(split_names, Full_Name, First_Name, Last_Name, sep =” “)print(combined_names)
Solution 18: Removing Duplicates
RCopy code# Create data frameduplicates <- data.frame( ID =c(1,2,2,3,4,4), Name =c(“Alice”,”Bob”,”Bob”,”Charlie”,”David”,”David”)) # Remove duplicatesunique_data <- distinct(duplicates, ID, .keep_all =TRUE)print(unique_data)
Solution 19: Wide-to-Long Transformation for Multiple Variables
RCopy code# Create data framestore_data <- data.frame( Store =c(“A”,”B”,”C”), Sales_Q1 =c(100,200,300), Sales_Q2 =c(150,250,350), Profit_Q1 =c(50,100,150), Profit_Q2 =c(75,125,175)) # Transform to long formatlong_store_data <- pivot_longer(store_data, cols =-Store, names_to =c(“Metric”,”Quarter”), names_sep =”_”)print(long_store_data)
Solution 20: Case Study – Real-Life Data Transformation
RCopy code# Use mtcars datasetdata(mtcars) # Filter rows where mpg > 20filtered_mtcars <- mtcars %>% filter(mpg >20) # Group by cyl and calculate average hpavg_hp_by_cyl <- filtered_mtcars %>% group_by(cyl)%>% summarize(Average_HP = mean(hp)) # Add Efficiency columnfiltered_mtcars <- filtered_mtcars %>% mutate(Efficiency = mpg / hp) # Arrange by Efficiencyresult <- filtered_mtcars %>% arrange(desc(Efficiency)) print(avg_hp_by_cyl)print(result)
These solutions provide detailed step-by-step applications of dplyr and tidyr. Let me know if you need further clarification or additional examples!
Part 1: Reshaping Data with tidyr
Exercise 1: Reshape Data Using gather
- Create a data frame with the following data:
- City: “New York”, “Los Angeles”, “Chicago”
- Temperature_Jan: 30, 50, 25
- Temperature_Feb: 32, 55, 28
- Temperature_Mar: 45, 60, 35
- Reshape the data into long format, with columns City, Month, and Temperature.
Exercise 2: Reshape Data Using spread
- Use the reshaped data from Exercise 1.
- Transform it back into wide format with columns for each month’s temperature.
Part 2: Handling Geospatial Data and Plotting Maps
Exercise 3: Plotting Points on a Map with ggmap
- Load the ggmap library and use Google Maps as the base map.
- Create a data frame with the following locations:
- Place: “Statue of Liberty”, “Hollywood Sign”, “Millennium Park”
- Latitude: 40.6892, 34.1341, 41.8826
- Longitude: -74.0445, -118.3215, -87.6226
- Plot these points on the map.
Exercise 4: Creating Interactive Maps with leaflet
- Install and load the leaflet package.
- Use the location data from Exercise 3.
- Create an interactive map with markers for each location. Customize each marker with popup information showing the Place.
Part 3: Creating Choropleth Maps
Exercise 5: Create a Choropleth Map
- Use the maps and ggplot2 libraries to create a basic choropleth map of the United States.
- Create a data frame containing state-level data for a hypothetical variable, such as Population.
- Visualize the data on a choropleth map, coloring each state based on its population.
Solutions
Solution 1: Reshape Data Using gather
R
Copy code
library(tidyr)
# Create data frame
weather_data <- data.frame(
City = c(“New York”, “Los Angeles”, “Chicago”),
Temperature_Jan = c(30, 50, 25),
Temperature_Feb = c(32, 55, 28),
Temperature_Mar = c(45, 60, 35)
)
# Reshape data to long format
long_weather <- gather(weather_data, key = “Month”, value = “Temperature”, -City)
print(long_weather)
Solution 2: Reshape Data Using spread
R
Copy code
# Reshape back to wide format
wide_weather <- spread(long_weather, key = “Month”, value = “Temperature”)
print(wide_weather)
Solution 3: Plotting Points on a Map with ggmap
R
Copy code
library(ggmap)
# Data for locations
locations <- data.frame(
Place = c(“Statue of Liberty”, “Hollywood Sign”, “Millennium Park”),
Latitude = c(40.6892, 34.1341, 41.8826),
Longitude = c(-74.0445, -118.3215, -87.6226)
)
# Register Google Maps API key (replace with your own API key)
# register_google(key = “YOUR_GOOGLE_API_KEY”)
# Get a base map
base_map <- get_map(location = “USA”, zoom = 4, maptype = “terrain”)
# Plot points on the map
ggmap(base_map) +
geom_point(data = locations, aes(x = Longitude, y = Latitude), color = “red”, size = 3) +
geom_text(data = locations, aes(x = Longitude, y = Latitude, label = Place), vjust = -1, size = 3) +
labs(title = “Points of Interest in the USA”)
Solution 4: Creating Interactive Maps with leaflet
R
Copy code
library(leaflet)
# Create an interactive map
leaflet(data = locations) %>%
addTiles() %>%
addMarkers(
~Longitude, ~Latitude,
popup = ~Place
) %>%
setView(lng = -98.35, lat = 39.50, zoom = 4)
Solution 5: Creating a Choropleth Map
R
Copy code
library(ggplot2)
library(maps)
# Get US map data
us_map <- map_data(“state”)
# Create sample data for states
state_data <- data.frame(
region = tolower(state.name),
Population = sample(100000:1000000, length(state.name))
)
# Merge map data with state data
choropleth_data <- merge(us_map, state_data, by = “region”)
# Plot choropleth map
ggplot(data = choropleth_data, aes(x = long, y = lat, group = group, fill = Population)) +
geom_polygon(color = “black”) +
scale_fill_gradient(low = “lightblue”, high = “darkblue”, name = “Population”) +
coord_fixed(1.3) +
labs(title = “Choropleth Map of US Population by State”) +
theme_minimal()
Key Takeaways
- Use tidyr functions like gather() and spread() to reshape data for better analysis.
- Geospatial data can be visualized interactively with leaflet or statically with ggmap.
- Choropleth maps provide an effective way to visualize geographical variations in data.
Exercise 6: Combine Multiple Columns Using unite
- Create a data frame:
- First_Name: “John”, “Jane”, “Doe”
- Last_Name: “Smith”, “Doe”, “Johnson”
- Age: 25, 30, 35
- Combine First_Name and Last_Name into a new column Full_Name using unite.
Exercise 7: Split a Single Column into Multiple Columns Using separate
- Use the data from Exercise 6.
- Split the Full_Name column back into First_Name and Last_Name.
Exercise 8: Pivot Data Using pivot_longer and pivot_wider
- Create a data frame:
- Region: “North”, “South”, “East”, “West”
- Q1_Sales: 100, 150, 200, 250
- Q2_Sales: 120, 180, 220, 270
- Convert the data to long format using pivot_longer.
- Convert it back to wide format using pivot_wider.
Exercise 9: Mapping Multiple Markers with leaflet
- Extend the location data from Exercise 3 with one more place:
- Place: “Golden Gate Bridge”
- Latitude: 37.8199
- Longitude: -122.4783
- Plot all the markers on an interactive map with a unique popup for each location.
Exercise 10: Create a Choropleth Map for World Data
- Use the rnaturalearth package to get world map data.
- Create a data frame for countries with random GDP values (e.g., Country and GDP).
- Visualize the GDP as a choropleth map using ggplot2.
Solutions
Solution 6: Combine Multiple Columns Using unite
R
Copy code
library(tidyr)
# Create data frame
name_data <- data.frame(
First_Name = c(“John”, “Jane”, “Doe”),
Last_Name = c(“Smith”, “Doe”, “Johnson”),
Age = c(25, 30, 35)
)
# Combine First_Name and Last_Name
combined_data <- unite(name_data, Full_Name, First_Name, Last_Name, sep = ” “)
print(combined_data)
Solution 7: Split a Single Column into Multiple Columns Using separate
R
Copy code
# Split Full_Name back into First_Name and Last_Name
split_data <- separate(combined_data, Full_Name, into = c(“First_Name”, “Last_Name”), sep = ” “)
print(split_data)
Solution 8: Pivot Data Using pivot_longer and pivot_wider
R
Copy code
# Create data frame
sales_data <- data.frame(
Region = c(“North”, “South”, “East”, “West”),
Q1_Sales = c(100, 150, 200, 250),
Q2_Sales = c(120, 180, 220, 270)
)
# Pivot to long format
long_sales <- pivot_longer(sales_data, cols = starts_with(“Q”),
names_to = “Quarter”, values_to = “Sales”)
print(long_sales)
# Pivot back to wide format
wide_sales <- pivot_wider(long_sales, names_from = Quarter, values_from = Sales)
print(wide_sales)
Solution 9: Mapping Multiple Markers with leaflet
R
Copy code
library(leaflet)
# Extend the location data
locations <- data.frame(
Place = c(“Statue of Liberty”, “Hollywood Sign”, “Millennium Park”, “Golden Gate Bridge”),
Latitude = c(40.6892, 34.1341, 41.8826, 37.8199),
Longitude = c(-74.0445, -118.3215, -87.6226, -122.4783)
)
# Create an interactive map
leaflet(data = locations) %>%
addTiles() %>%
addMarkers(
~Longitude, ~Latitude,
popup = ~Place
) %>%
setView(lng = -98.35, lat = 39.50, zoom = 4)
Solution 10: Create a Choropleth Map for World Data
R
Copy code
library(ggplot2)
library(rnaturalearth)
library(dplyr)
# Get world map data
world_map <- ne_countries(scale = “medium”, returnclass = “sf”)
# Create random GDP data for countries
country_data <- data.frame(
name = world_map$name,
GDP = runif(nrow(world_map), min = 1000, max = 50000) # Random GDP values
)
# Merge map data with GDP data
choropleth_world <- merge(world_map, country_data, by.x = “name”, by.y = “name”)
# Plot choropleth map
ggplot(data = choropleth_world) +
geom_sf(aes(fill = GDP)) +
scale_fill_gradient(low = “lightgreen”, high = “darkgreen”, name = “GDP (in USD)”) +
labs(title = “World GDP by Country”) +
theme_minimal()
Unit 10
Lab Assignment: Advanced R Programming Concepts
Objective:
This lab assignment helps you practice advanced concepts in R, including error handling, debugging, working with dates and times, and exploring tools for handling big data (data.table and parallel processing).
Part 1: Error Handling and Debugging
Exercise 1: Try-Catch for Error Handling
- Write a function, divide_numbers(a, b), that divides two numbers and handles division by zero using tryCatch.
- If division by zero occurs, return “Error: Division by zero!”.
Exercise 2: Debugging with browser()
- Write a function, calculate_area(length, width), to calculate the area of a rectangle.
- Add debugging with browser() to inspect the function’s environment when length or width is missing.
Part 2: Working with Dates and Times
Exercise 3: Parsing Dates
- Create a vector of date strings:
c(“2024-12-25”, “2023-01-01”, “2024-07-04”). - Convert the vector to Date objects using as.Date.
Exercise 4: Formatting Dates and Times
- Use the Sys.Date() and Sys.time() functions to display the current date and time.
- Format the date as “Day, Month DD, YYYY” (e.g., “Tuesday, December 25, 2024”).
Exercise 5: Calculating Differences Between Dates
- Create two date objects:
- start_date <- as.Date(“2024-01-01”)
- end_date <- as.Date(“2024-12-31”)
- Calculate the difference in days between the two dates.
Part 3: R for Big Data
Exercise 6: Working with data.table
- Convert a data.frame with 1 million rows into a data.table.
- Perform basic operations like filtering, grouping, and summarizing on the data.table.
Exercise 7: Parallel Processing with parallel
- Write a function to calculate the square of a number.
- Use mclapply (from the parallel package) to calculate the squares of numbers from 1 to 100 in parallel.
Solutions
Solution 1: Try-Catch for Error Handling
R
Copy code
# Function to divide numbers with error handling
divide_numbers <- function(a, b) {
tryCatch(
{
result <- a / b
return(result)
},
error = function(e) {
return(“Error: Division by zero!”)
}
)
}
# Example usage
print(divide_numbers(10, 2)) # Outputs: 5
print(divide_numbers(10, 0)) # Outputs: “Error: Division by zero!”
Solution 2: Debugging with browser()
R
Copy code
# Function to calculate area with debugging
calculate_area <- function(length, width) {
if (missing(length) || missing(width)) {
browser() # Debugging point
}
return(length * width)
}
# Example usage
# Uncomment to debug
# calculate_area(10) # Debugging session starts here
Solution 3: Parsing Dates
R
Copy code
# Date strings
date_strings <- c(“2024-12-25”, “2023-01-01”, “2024-07-04”)
# Convert to Date objects
date_objects <- as.Date(date_strings)
print(date_objects)
Solution 4: Formatting Dates and Times
R
Copy code
# Current date and time
current_date <- Sys.Date()
current_time <- Sys.time()
# Format date
formatted_date <- format(current_date, “%A, %B %d, %Y”)
print(formatted_date)
# Display current time
print(current_time)
Solution 5: Calculating Differences Between Dates
R
Copy code
# Date objects
start_date <- as.Date(“2024-01-01”)
end_date <- as.Date(“2024-12-31”)
# Calculate difference in days
date_difference <- as.numeric(difftime(end_date, start_date, units = “days”))
print(date_difference)
Solution 6: Working with data.table
R
Copy code
library(data.table)
# Create a data frame with 1 million rows
df <- data.frame(
ID = 1:1000000,
Value = runif(1000000, min = 1, max = 100)
)
# Convert to data.table
dt <- as.data.table(df)
# Filter rows where Value > 50
filtered_dt <- dt[Value > 50]
# Group by rounded Value and summarize
summary_dt <- dt[, .(Count = .N, Avg_Value = mean(Value)), by = .(Rounded_Value = round(Value))]
print(summary_dt)
Solution 7: Parallel Processing with parallel
R
Copy code
library(parallel)
# Function to calculate square
square_function <- function(x) {
return(x^2)
}
# Use parallel processing
squared_numbers <- mclapply(1:100, square_function, mc.cores = detectCores() – 1)
print(unlist(squared_numbers))
Key Takeaways
- Error handling and debugging ensure robust and maintainable code.
- Dates and times in R are powerful tools for temporal analysis.
- The data.table package and parallel processing are essential for handling big data efficiently in R.
Let me know if you need additional examples or further clarifications!
Lab Assignment: Applying Visualization Techniques to Real World Datasets and Developing a Visualization Dashboard
Objective:
- To learn how to apply data visualization techniques to real-world datasets.
- To develop an interactive visualization dashboard for showcasing insights from the data.
Tools Required:
- Python Programming Language
- Libraries: Pandas, Matplotlib, Seaborn, Plotly, Dash
- Real-world dataset (e.g., sales data, weather data, healthcare data, etc.)
Part 1: Case Study – Visualizing Real-World Data
Task:
Choose a real-world dataset, such as:
- Sales Data (from a retail store or online shop)
- Weather Data (temperature, precipitation, etc. over time)
- Healthcare Data (patient records, hospital admissions)
- Financial Data (stock prices, cryptocurrency prices)
Steps to follow:
- Data Acquisition:
-
- Download a real-world dataset from a reliable source, such as Kaggle, government open data portals, or other public datasets.
- Example dataset: “Retail Sales Data” (monthly sales, store info, product details).
- Data Preprocessing:
-
- Import the dataset using Pandas and inspect the data.
- Clean the data by handling missing values, removing duplicates, and ensuring proper data types.
pythonCopy codeimport pandas as pd # Load datadata = pd.read_csv(‘sales_data.csv’) # Inspect dataprint(data.head()) # Handle missing valuesdata = data.fillna(method=’ffill’) # Forward fill missing data
- Data Visualization:
-
- Create visualizations to represent key trends in the data, such as:
- Line Plot for trends over time.
- Bar Chart for category comparison.
- Heatmap to visualize correlations or missing data patterns.
- Scatter Plot to show relationships between two variables.
- Create visualizations to represent key trends in the data, such as:
Example code for visualization using Matplotlib and Seaborn:
pythonCopy codeimport matplotlib.pyplot as pltimport seaborn as sns # Line Plot (Time Series)plt.figure(figsize=(10, 6))plt.plot(data[‘Date’], data[‘Sales’])plt.title(‘Sales Over Time’)plt.xlabel(‘Date’)plt.ylabel(‘Sales’)plt.show() # Bar Chart (Category Comparison)category_sales = data.groupby(‘ProductCategory’)[‘Sales’].sum()category_sales.plot(kind=’bar’, figsize=(10, 6))plt.title(‘Total Sales by Product Category’)plt.xlabel(‘Product Category’)plt.ylabel(‘Sales’)plt.show()
- Interpretation:
-
- Analyze the visualizations and interpret key insights (e.g., highest sales months, product categories with the highest sales, etc.).
Part 2: Project Work – Developing a Visualization Dashboard
Task:
Develop an interactive dashboard to showcase your visualizations. Use the Dash framework by Plotly to create a simple interactive dashboard.
Steps to follow:
- Install Required Libraries: Ensure you have the necessary libraries installed.
bashCopy codepip install dash pandas plotly
- Basic Dash App Setup: Create a simple Dash app to display your visualizations.
pythonCopy codeimport dashimport dash_core_components as dccimport dash_html_components as htmlfrom dash.dependencies import Input, Outputimport plotly.express as pximport pandas as pd # Load datasetdata = pd.read_csv(‘sales_data.csv’) # Initialize Dash appapp = dash.Dash(__name__) # Layout of the dashboardapp.layout = html.Div(children=[ html.H1(children=’Sales Data Visualization Dashboard’), dcc.Graph(id=’sales-trend’, figure=px.line(data, x=’Date’, y=’Sales’, title=’Sales Over Time’) ), dcc.Graph(id=’category-sales’, figure=px.bar(data, x=’ProductCategory’, y=’Sales’, title=’Sales by Category’) )]) # Run the serverif __name__ == ‘__main__’: app.run_server(debug=True)
- Add Interactivity: Add dropdowns or sliders to make the dashboard interactive. For example, allow the user to filter by product category or date range.
pythonCopy codeapp.layout = html.Div(children=[ html.H1(children=’Sales Data Visualization Dashboard’), dcc.Dropdown(id=’category-dropdown’, options=[ {‘label’: category, ‘value’: category} for category in data[‘ProductCategory’].unique() ], value=data[‘ProductCategory’].unique()[0], style={‘width’: ‘50%’} ), dcc.Graph(id=’filtered-category-sales’)]) @app.callback( Output(‘filtered-category-sales’, ‘figure’), Input(‘category-dropdown’, ‘value’))defupdate_category_sales(selected_category): filtered_data = data[data[‘ProductCategory’] == selected_category]return px.bar(filtered_data, x=’ProductCategory’, y=’Sales’, title=f’Sales for {selected_category}’)
- Run the Application:
-
- Run the app and open the local server in your browser to interact with the dashboard.
- Explore the visualizations and make sure the dashboard works as expected.
Solution Summary:
- Data Acquisition & Preprocessing:
-
- Import data and clean it by handling missing values and converting data types.
- Data Visualization:
-
- Created different visualizations like line plots, bar charts, and scatter plots using Matplotlib and Seaborn.
- Gained insights from visualizing sales data trends over time and by product category.
- Dashboard Development:
-
- Developed an interactive dashboard using Dash that allows users to filter the data and view updated visualizations.
- The dashboard provides insights on sales trends and allows users to interact with various visual components like dropdowns and graphs.
Practical Assignment 1: Exploring Student Grades Data
Objective:
To explore and visualize student grades data to understand patterns and trends.
Dataset:
- A dataset of student grades (e.g., student names, subjects, and scores).
Steps to Follow:
- Data Loading: Load the dataset into a Pandas DataFrame.
python
Copy code
import pandas as pd
# Sample data for student grades
data = {
‘Student’: [‘Alice’, ‘Bob’, ‘Charlie’, ‘David’, ‘Eva’],
‘Math’: [90, 80, 70, 85, 95],
‘Science’: [88, 92, 78, 85, 90],
‘English’: [85, 80, 90, 88, 92]
}
df = pd.DataFrame(data)
print(df)
- Data Visualization:
- Visualize the student scores using bar charts.
- Create a heatmap to show correlation between subjects.
python
Copy code
import matplotlib.pyplot as plt
import seaborn as sns
# Bar chart of student scores by subject
df.set_index(‘Student’).plot(kind=’bar’, figsize=(10, 6))
plt.title(‘Student Scores by Subject’)
plt.ylabel(‘Score’)
plt.show()
# Correlation heatmap
correlation = df.drop(‘Student’, axis=1).corr()
sns.heatmap(correlation, annot=True, cmap=’coolwarm’, cbar=True)
plt.title(‘Correlation Heatmap of Scores’)
plt.show()
- Interpretation:
- The bar chart gives a clear comparison of scores by student and subject.
- The heatmap helps identify the correlation between subjects (e.g., higher correlation between Math and Science).
Practical Assignment 2: Analyzing Sales Data for a Retail Store
Objective:
To analyze monthly sales data for a retail store and visualize sales trends over time.
Dataset:
- A dataset with columns like: Date, Product, Sales.
Steps to Follow:
- Data Loading: Load the sales data into a Pandas DataFrame.
python
Copy code
data = {
‘Date’: [‘2023-01-01’, ‘2023-02-01’, ‘2023-03-01’, ‘2023-04-01’, ‘2023-05-01’],
‘Sales’: [5000, 6000, 5500, 7000, 7500],
}
df = pd.DataFrame(data)
df[‘Date’] = pd.to_datetime(df[‘Date’])
print(df)
- Data Visualization:
- Plot a line graph to visualize sales trends over time.
python
Copy code
plt.figure(figsize=(10, 6))
plt.plot(df[‘Date’], df[‘Sales’], marker=’o’, linestyle=’-‘, color=’b’)
plt.title(‘Monthly Sales Trends’)
plt.xlabel(‘Date’)
plt.ylabel(‘Sales ($)’)
plt.grid(True)
plt.show()
- Interpretation:
- The line graph will show the sales trends, and you can easily spot any increase or decrease in sales over the months.
Mini-Project 1: Movie Rating Dashboard
Objective:
Create a dashboard to visualize movie ratings and their genres.
Dataset:
- A dataset with columns like: Movie Name, Genre, Rating.
Steps to Follow:
- Data Loading: Load the dataset into a Pandas DataFrame.
python
Copy code
data = {
‘Movie’: [‘Inception’, ‘Titanic’, ‘Avatar’, ‘Interstellar’, ‘The Dark Knight’],
‘Genre’: [‘Sci-Fi’, ‘Romance’, ‘Action’, ‘Sci-Fi’, ‘Action’],
‘Rating’: [8.8, 7.8, 8.0, 8.6, 9.0]
}
df = pd.DataFrame(data)
print(df)
- Data Visualization:
- Create a bar chart for the movie ratings by genre.
python
Copy code
import seaborn as sns
plt.figure(figsize=(10, 6))
sns.barplot(x=’Genre’, y=’Rating’, data=df, palette=’viridis’)
plt.title(‘Movie Ratings by Genre’)
plt.show()
- Project Enhancement – Create a Dashboard: Use Dash to create an interactive dashboard where users can filter movies by genre and view their ratings.
python
Copy code
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
# Dash app setup
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1(“Movie Rating Dashboard”),
dcc.Dropdown(
id=’genre-dropdown’,
options=[{‘label’: genre, ‘value’: genre} for genre in df[‘Genre’].unique()],
value=’Sci-Fi’,
),
dcc.Graph(id=’rating-graph’)
])
@app.callback(
Output(‘rating-graph’, ‘figure’),
Input(‘genre-dropdown’, ‘value’)
)
def update_graph(selected_genre):
filtered_df = df[df[‘Genre’] == selected_genre]
fig = px.bar(filtered_df, x=’Movie’, y=’Rating’, color=’Genre’, title=f”Ratings for {selected_genre} Movies”)
return fig
if __name__ == ‘__main__’:
app.run_server(debug=True)
- Interpretation:
- The dashboard will show ratings for different movies by genre, and users can select different genres from the dropdown menu.
Mini-Project 2: Weather Data Visualization
Objective:
To analyze and visualize weather data like temperature and rainfall patterns.
Dataset:
- A dataset with columns like: Date, Temperature (°C), Rainfall (mm).
Steps to Follow:
- Data Loading: Load the weather data into a Pandas DataFrame.
python
Copy code
data = {
‘Date’: [‘2023-01-01’, ‘2023-01-02’, ‘2023-01-03’, ‘2023-01-04’, ‘2023-01-05’],
‘Temperature’: [22, 24, 19, 21, 23],
‘Rainfall’: [0, 2, 5, 0, 1]
}
df = pd.DataFrame(data)
df[‘Date’] = pd.to_datetime(df[‘Date’])
print(df)
- Data Visualization:
- Plot the temperature over time.
- Plot the rainfall over time.
python
Copy code
# Temperature plot
plt.figure(figsize=(10, 6))
plt.plot(df[‘Date’], df[‘Temperature’], marker=’o’, color=’r’, label=’Temperature (°C)’)
plt.title(‘Temperature Over Time’)
plt.xlabel(‘Date’)
plt.ylabel(‘Temperature (°C)’)
plt.grid(True)
plt.show()
# Rainfall plot
plt.figure(figsize=(10, 6))
plt.bar(df[‘Date’], df[‘Rainfall’], color=’b’, label=’Rainfall (mm)’)
plt.title(‘Rainfall Over Time’)
plt.xlabel(‘Date’)
plt.ylabel(‘Rainfall (mm)’)
plt.grid(True)
plt.show()
- Interpretation:
- The temperature plot helps understand how the temperature fluctuated over time.
- The rainfall plot shows how much rain fell on each date.
Conclusion:
These practical assignments and mini-projects help you practice various skills like data loading, cleaning, and visualization. By exploring different types of data, you can develop a solid foundation in data analysis and visualization techniques.
Course Code: LMC0301 | Course Title:Visualization with R Programming (3 Credits) |
Course Objectives: –
Ø To introduce the fundamentals of data visualization using R programming. Ø To enable students to manipulate and visualize data effectively using various R libraries. Ø To develop proficiency in creating informative and interactive visualizations for data analysis and presentation. Ø To understand the principles of visual perception and how they influence data representation. |
|
BTL- Bloom’s Taxonomy Level. 1- Understand, 2- Remember, 3- Apply, 4- Analyze, 5- Evaluate, 6- Create |
Course Contents:
Unit | Unit Description | Learning Outcome |
1 | Introduction to Data Visualization: Overview of data visualization, importance in data analysis, introduction to R programming, setting up R environment, basic R syntax. | This module has been designed as per BTL 1 & 2. |
2 | Data Types and Structures in R: Vectors, matrices, lists, data frames, importing and exporting data, data cleaning and transformation. | This module has been designed as per BTL 2 & 3. |
3 | Basic Plotting with R: Introduction to base graphics in R, scatter plots, line graphs, bar charts, histograms, pie charts, and box plots. | This module has been designed as per BTL 3. |
4 | Advanced Graphics with ggplot2: Introduction to ggplot2, understanding the grammar of graphics, layers, scales, themes, and facets in ggplot2. | This module has been designed as per BTL 3 & 4. |
5 | Data Manipulation with dplyr and tidyr: Using dplyr for data manipulation, filtering, selecting, mutating, summarizing data, tidying data with tidyr, reshaping data. | This module has been designed as per BTL 3 & 4. |
6 | Statistical Data Visualization: Visualizing distributions, statistical summaries, creating plots for regression analysis, visualizing correlations, and understanding distributions. | This module has been designed as per BTL 4. |
7 | Interactive Visualizations with plotly and Shiny: Creating interactive plots with plotly, introduction to Shiny for building interactive web applications, integrating plots with Shiny apps. | This module has been designed as per BTL 4 & 5. |
8 | Time Series Visualization: Plotting time series data, understanding trends and seasonality, using ts objects in R, advanced time series plots. | This module has been designed as per BTL 4 & 5. |
9 | Geospatial Data Visualization: Handling geospatial data in R, plotting maps using ggmap and leaflet, creating choropleth maps, visualizing spatial data. | This module has been designed as per BTL 4 & 5. |
10 | Case Studies and Project: Applying visualization techniques to real-world datasets, creating comprehensive data visualizations, project work on developing a visualization dashboard. | This module has been designed as per BTL 5 & 6. |
Textbooks:
- Wickham, H. (2016). ggplot2: Elegant Graphics for Data Analysis. Springer.
- Chang, W. (2018). R Graphics Cookbook: Practical Recipes for Visualizing Data. O’Reilly Media.
Reference Books:
- Matloff, N. (2011). The Art of R Programming: A Tour of Statistical Software Design. No Starch Press.
- Kabacoff, R. I. (2015). R in Action: Data Analysis and Graphics with R. Manning Publications.
(Bloom’s Taxonomy: BT level 1: Remembering; BT level 2: Understanding; BT level 3: Applying; BT level 4: Analyzing; BT level 5: Evaluating; BT level 6: Creating)
Course Code: LMC0302 | Course Title:Advanced Data Communication and Network(3 Credits) |
Course Objectives: –
Ø Students will learn the basic concepts of computer networks. Ø To understand the concept of network topology. Ø To understand network management systems. Ø To gain knowledge of Client-Server applications. Ø To understand Communication and Network. |
Course Contents:
Sr. No. | Unit No. / Unit Description | Learning Outcome |
1 | Unit I: Introduction – Overview of Data Communication and Networks, Need for computer communication, Goals of communication systems/Networking, Transmission Modes, Transmission Media: Guided: Twisted Pair, Coaxial and Fiber-Optic Cables, Unguided Media: Radio, VHF, Microwaves, and Satellite, Topologies: Star, Mesh, Bus, etc. | Students will be able to achieve BL 1 (Remembering). |
2 | Unit II: Physical Layer-Multichannel Data Communication: Message, Circuits, Packets (Connection-Oriented vs Connectionless Services), Components of LAN, WAN, MAN, Multiplexing: FDM, TDM, and WDM, Protocol Layering: ISO/OSI Reference Model, TCP/IP Reference Model, OSI vs TCP/IP | Students will be able to achieve BL 1 and 2 (Remembering and Understanding). |
3 | Unit III: Network Layer-IPv4 addresses – Network and Host part, Network Masks, Network addresses, and Broadcast addresses, Sub-net Masking, Super Net Masking, Numerical based on IP Address, Address Classes, IPv4 Structure, IP routing concept, Distance Vector algorithm, Routing Table, IPv6 Structure, Addresses. | Students will be able to achieve BL 1 and 2 (Remembering and Understanding). |
4 | Unit IV: Transport Layer-Transport Services, Elements of Transport Protocols, Connection Management, Connection Management, TCP and UDP Protocols | Students will be able to achieve BL 1 and 3 (Remembering and Applying). |
5 | Unit V: Application Layer-DNS and DNS Servers, DNS and DNS Servers, Electronic Mail: Architecture and Services, Electronic Mail: Architecture and Services, Message Format, SMTP, Mail Gateways, FTP, WWW: Introduction, Static and Dynamic web pages, WWW pages and browsing, HTTP request and response, Basics of DHCP. | Students will be able to achieve BL 3 and 4 (Applying and Analyzing). |
6 | Unit VI: Common Network Architecture-X.25 Networks, Ethernet (Standard and Fast): Frame format and specifications, Wireless LAN’s – 802.11x, 802.3, Bluetooth, etc. | Students will be able to achieve BL 3 and 4 (Applying and Analyzing). |
7 | Unit VII: Network Security –Threat: Active and Passive Attacks, Cryptography: Symmetric and Asymmetric Key Cryptography,DigitalSignature, Firewall, Types of Firewall | Students will be able to achieve BL 3 and 4 (Applying and Analyzing). |
8 | Unit VIII: Network Management– OSI Network Management Model, ISO Network Management Functions, Remote Network Monitoring (RMON), Network Management Tools, Wireless Network Management | Students will be able to achieve BL 1, 2, and 3 (Remembering, Understanding, and Applying). |
9 | Unit IX: Emerging Trends and Technologies– Software-Defined Networking (SDN), Network Function Virtualization (NFV), Internet of Things (IoT), Cloud Computing and Networking, Cloud Computing and Networking,Future Internet Architectures | Students will be able to achieve BL 3 and 5 (Applying and Evaluating). |
10 | Unit X: Broadband Network Management – ATM Networks, Future Internet Architectures, Broadband Networks and Services, Broadband Networks and Services, ATM Technology, ATM Technology | Students will be able to achieve BL 3 and 4 (Applying and Analyzing). |
Textbooks and References:
- Data and Computer Communications by William Stallings.
- Computer Networking: A Top-Down Approach by James F. Kurose and Keith W. Ross.
- Data Communications and Networking by Behrouz A. Forouzan.
(Bloom’s Taxonomy: BT level 1: Remembering; BT level 2: Understanding; BT level 3: Applying; BT level 4: Analyzing; BT level 5: Evaluating; BT level 6: Creating)
Course Code: LMC0303 | Course Title:Advance Python Programming (3 Credits) |
Course Objectives: –
Ø Utilize advanced Python features for efficient programming. Ø Develop web applications and APIs using Python frameworks. Ø Apply Python in data manipulation, analysis, and machine learning. Ø Implement concurrency and parallelism for optimized performance. Ø Explore Python’s application in networking, automation, and cloud computing. |
|
BTL- Bloom’s Taxonomy Level. 1- Understand, 2- Remember, 3- Apply, 4- Analyze, 5- Evaluate, 6- Create |
Course Contents
Unit | Unit Description | Learning Outcome |
1 | Advanced Python Syntax: Iterators, generators, decorators, and context managers. Understanding the nuances of Python syntax. | This module has been designed as per BTL 4. |
2 | Advanced Object-Oriented Programming:Metaclasses, abstract classes, multiple inheritance, and design patterns in Python. | This module has been designed as per BTL 4 & 5. |
3 | Data Manipulation and Analysis: Using libraries like NumPy, Pandas for data analysis, performing complex data manipulations, and understanding dataframes. | This module has been designed as per BTL 3 & 4. |
4 | Working with APIs: Understanding RESTful APIs, consuming APIs using Python, and building simple APIs with Flask/Django. | This module has been designed as per BTL 4 & 5. |
5 | Web Development with Python: Basics of web development using Django/Flask, setting up a web server, creating and managing views, and handling forms and templates. | This module has been designed as per BTL 5. |
6 | Concurrency and Parallelism: Understanding threading, multiprocessing, asynchronous programming with async/await, and concurrent futures. | This module has been designed as per BTL 4 & 5. |
7 | Testing and Debugging: Writing unit tests, using testing frameworks like pytest, and debugging techniques in Python. | This module has been designed as per BTL 5. |
8 | Python for Data Science: Introduction to machine learning using Python, basics of scikit-learn, and performing exploratory data analysis. | This module has been designed as per BTL 5 & 6. |
9 | Networking and Sockets Programming: Introduction to network programming, creating sockets, handling client-server communication, and working with protocols. | This module has been designed as per BTL 4 & 5. |
10 | Advanced Topics in Python: Overview of Python’s role in cloud computing, working with AWS/GCP SDKs, and automation scripting. | This module has been designed as per BTL 6. |
Textbooks:
Reference Books:
|
(Bloom’s Taxonomy: BT level 1: Remembering; BT level 2: Understanding; BT level 3: Applying; BT level 4: Analyzing; BT level 5: Evaluating; BT level 6: Creating)
Course Code: LMC0304 | Course Title:Research Methodology (3 Credits) |
Course Objectives: –
Ø To provide an understanding of research concepts and methodologies. Ø To equip students with the skills to design and conduct research studies. Ø To enable students to analyze data and interpret research findings. Ø To develop the ability to critically evaluate research literature. Ø To guide students in the preparation of research proposals and reports. |
|
BTL- Bloom’s Taxonomy Level. 1- Understand, 2- Remember, 3- Apply, 4- Analyze, 5- Evaluate, 6- Create |
Course Contents:
Unit | Unit Description | Learning Outcome |
1 | Introduction to Research Methodology: Meaning, Objectives, Types of Research, Research Approaches, Research Process. | Students will gain a foundational understanding of research concepts (BTL 1). |
2 | Literature Review: Importance of Literature Review, Sources of Information, Reviewing Process, Writing a Review. | Students will learn how to conduct and synthesize literature reviews (BTL 2). |
3 | Research Design: Research Problem Formulation, Hypothesis Development, Research Design Types: Exploratory, Descriptive, Experimental. | Students will understand the design and planning of research studies (BTL 3). |
4 | Data Collection Methods: Primary and Secondary Data, Sampling Techniques, Questionnaire Design, Interviews, Observation. | Students will acquire skills in data collection methods and tools (BTL 2 & 3). |
5 | Measurement and Scaling: Types of Scales, Measurement Errors, Reliability and Validity of Measurements. | Students will learn how to measure variables and assess their reliability and validity (BTL 3). |
6 | Data Analysis: Descriptive and Inferential Statistics, Hypothesis Testing, Use of Software Tools for Data Analysis. | Students will gain skills in analyzing data using statistical techniques (BTL 3 & 4). |
7 | Qualitative Research: Characteristics, Techniques, and Methods, Content Analysis, Case Study Method. | Students will understand and apply qualitative research methods (BTL 2 & 3). |
8 | Research Report Writing: Structure of Research Report, Writing Techniques, Presentation of Data, Referencing Styles, Plagiarism. | Students will develop skills in writing and presenting research reports (BTL 4 & 5). |
9 | Ethical Issues in Research: Ethical Considerations, Informed Consent, Confidentiality, Publication Ethics. | Students will understand the ethical aspects of conducting research (BTL 4). |
10 | Emerging Trends in Research: Big Data Analytics, Artificial Intelligence in Research, Multidisciplinary Research, Trends in Publishing. | Students will be aware of the latest trends and innovations in research (BTL 4 & 5). |
Textbooks:
- C.R. Kothari & Gaurav Garg, “Research Methodology: Methods and Techniques,” New Age International Publishers, 4th Edition, 2019.
- Ranjit Kumar, “Research Methodology: A Step-by-Step Guide for Beginners,” SAGE Publications, 4th Edition, 2014.
Reference Books:
- John W. Creswell, “Research Design: Qualitative, Quantitative, and Mixed Methods Approaches,” SAGE Publications, 5th Edition, 2017.
- Zikmund, Babin, Carr & Griffin, “Business Research Methods,” Cengage Learning, 9th Edition, 2013.
(Bloom’s Taxonomy: BT level 1: Remembering; BT level 2: Understanding; BT level 3: Applying; BT level 4: Analyzing; BT level 5: Evaluating; BT level 6: Creating)
Course Code: LMC0340 | Course Title:Artificial Intelligence and Machine Learning (3 Credits) |
Course Objectives: –
Ø Understand the foundational concepts and methods in Artificial Intelligence (AI) and Machine Learning (ML). Ø Implement and apply machine learning algorithms for different types of problems. Ø Analyse the trade-offs between different AI and ML techniques in various contexts. Ø Develop AI systems that can solve real-world problems using appropriate ML models. Ø Evaluate AI and ML models based on performance metrics and improve them through hyper parameter tuning and cross-validation techniques. |
|
BTL- Bloom’s Taxonomy Level. 1- Understand, 2- Remember, 3- Apply, 4- Analyse, 5- Evaluate, 6- Create |
Artificial Intelligence and Machine Learning (3 Credits)
Course Contents:
Unit | Unit Description | Learning Outcome |
1 |
Introduction to Artificial Intelligence- Definition and Scope of AI, History and Evolution of AI, Types of AI: Narrow AI, General AI, Super intelligent AI, AI vs Machine Learning vs Deep Learning, AI applications in various domains. |
Students will gain a foundational understanding of Artificial Intelligence (BTL 1). |
2 |
Problem Solving and Search Algorithms-Problem Representation and Formulation, Uninformed Search Algorithms (BFS, DFS, Uniform Cost Search),, Informed Search Algorithms (A*, Greedy Search), Heuristic functions, Optimization in Search Algorithms |
Students will Understand and remember problem solving and search algorithms (BTL 1 and 2). |
3 |
Knowledge Representation and Reasoning-Introduction to Knowledge Representation and reasoning, Logic-based Representation in AI, PropositionalLogic and Predicate Logic, Rule-based Systems, ForwardChanning and Backward Chaining, Inference and Reasoning Techniques |
Students will understand and apply Knowledge representation and Reasoning Techniques(BTL2 and 3). |
4 |
Machine Learning: Introduction and Overview- Definition of Machine Learning, Supervised, Unsupervised, and Reinforcement Learning, Overview of ML Algorithms, Difference between AI and ML, Basic Applications of ML |
Students will understand machine Learning concept (BTL 1). |
5 |
Supervised Learning: Regression and Classification,Linear Regression, Logistic Regression, Decision Trees, Support Vector Machines (SVM), K-Nearest Neighbors (KNN) |
Students will understand the concepts of supervised Learning (BTL 2). |
6 |
Unsupervised Learning: Clustering and Dimensionality Reduction, K-Means Clustering, Hierarchical Clustering, Principal Component Analysis (PCA), t-SNE for Dimensionality Reduction, Applications in Data Preprocessing. |
Students will understand and apply unsupervisedlearning (BTL 3). |
7 |
Neural Networks and Deep Learning, Introduction to Neural Networks, Perceptron and Multi-Layer Perceptron (MLP), Backpropagation Algorithm, Deep Neural Networks (DNNs), Convolutional Neural Networks (CNNs) |
Students will able to analyse difference between AI, ML and DL and will understand NN. (BTL 1 and 4). |
8 |
Model Evaluation and Improvement- Introduction to Evaluation and Improvement , Performance Metrics: Accuracy, Precision, Recall, F1-score, Cross-Validation Techniques, Hyperparameter Tuning, Overfitting and Underfitting,Regularization Methods: L1, L2 |
Students will be able to evaluate the model (BTL 5) |
9 |
Reinforcement Learning – Overview of Reinforcement Learning, Markov Decision Processes (MDPs), Q-Learning Algorithm, Policy Gradient Methods, Applications of RL in Games and Robotics |
Students will be able remember and understand reinforcement learning.(BTL 1 and 2). |
10 |
Natural Language Processing (NLP)- Introduction to NLP, Text Pre-processing and Tokenization, Bag of Words, TF-IDF Models, Named Entity Recognition (NER), Sentiment Analysis using ML |
Students will understand and remember NLP. (BTL 1 and 2). |
11 |
AI Ethics and Societal Impacts- Ethical Issues in AI and ML, Bias and Fairness in AI Systems, Transparency and Explainability of ML Models, Privacy and Security in AI, Societal Impact of AI and Automation |
Students will be able analyse and evaluate Ethical issues, Privacy concerns in AI(BTL 4 & 5). |
12 |
Future Trends in AI and Machine Learning- AI in Healthcare, Autonomous Vehicles, and Finance, Transfer Learning, Quantum Machine Learning, AI and Creativity: Art, Music, and Design, Emerging Trends and Technologies in AI |
Students will be aware of the latest trends and analyse different Trends in AI (BTL 4 & 5). |
Textbooks:
- “Artificial Intelligence: A Modern Approach” by Stuart Russell and Peter Norvig.
- “Pattern Recognition and Machine Learning” by Christopher Bishop.
Reference Books:
- Deep Learning” by Ian Goodfellow, YoshuaBengio, and Aaron Courville.
- “Machine Learning: A Probabilistic Perspective” by Kevin P. Murphy.
CloudComputingSyllabus
CourseCode:LMC0341 | CourseTitle:CloudComputing(3Credits) |
CourseLearningOutcomes
· Understandthefundamentalconceptsandarchitectureofcloudcomputing. · Analysevariouscloudservicemodelsanddeploymentmodels. · Explorevirtualizationtechnologiesandtheirroleincloudcomputing. · Understandcloudstoragesolutionsanddatamanagementinthecloud. · Implementcloud-basedapplicationsandservices. |
|
*BTL-Bloom’sTaxonomyLevel.1-Understand,2-Remember,3-Apply,4-Analyze,5-
Evaluate,6-Create |
CourseContents
Sr.No | UnitNo./Unitdescription | UnitOutcome |
1 | Unit 1- Introduction to Cloud Computing: Definition and Characteristics, Cloud Computing Models: IaaS, PaaS, SaaS, Architecture, Evolution, Cloud Ecosystem, Benefits and Challenges of Cloud Computing. | Students will be able to understand Cloud Computing. (BTL 1-Understanding). |
2 | Unit 2- Cloud Service Models: Overview of IaaS, PaaS, SaaS, Key Features of Each Model, Examples of Cloud Service Providers (AWS, Azure, Google Cloud), Comparing and Contrasting IaaS, PaaS,SaaS | Students will be able to understand & rememberservicemodels.(BTL1-
Understand, BTL 2- Remember). |
3 | Unit 3-Public Cloud-Private Cloud, Hybrid Cloud, Community Cloud, Deployment Model Selection Criteria, Benefits and Limitations of Each Model, Use Cases of Each Deployment Model | Students will be able to remember and use Cloud models. (BTL 3- Apply). |
4 | Unit 4- Virtualization in Cloud Computing– Introduction to Virtualization, Hypervisor Types and Architectures, Virtual Machines and Virtual Networks, Virtualization and Cloud Computing
Integration |
Students will be able to use in virtual machines. (BTL3- Apply). |
5 | Unit 5-Cloud Storage Overview– Types of Cloud Storage: Block, File, Object, Cloud Storage Providers, Storage Management Techniques, Data Replication and Availability | Students will be able to use cloud cloud storage. (BTL 6- Create). |
6 | Unit 6- Data Management and Big Data in the Cloud– Data Management in Cloud Environments, Cloud Databases: NoSQL, SQL Databases, Data Sharding and Partitioning, Big Data Technologies in Cloud (Hadoop, Spark). | Students will be able analyze and evaluate Data on Cloud. (BTL 4- analyze, BTL 5- Evaluate). |
7 | Unit 7: Cloud Application Development – Introduction to Cloud Application Development, Cloud APIs and SDKs, Cloud-Based Application Deployment, Cloud App Development Best Practices | Students will be able analyze importance of applications on cloud. (BTL 4- Analyze). |
8 | Unit 8: Cloud Computing Tools and Platforms- Introduction to Cloud Platforms (AWS, Azure), Cloud Management Tools, Automation and Orchestration Tools, Monitoring and Performance Tuning Tool | Students will be able to understand cloud Tools. (BTL 1-Understand and BTL 2- Remember). |
9 | Unit9:CloudSecurityChallenges-SecurityRisks inCloudComputing,CloudDataProtectionTechniques, Cloud Security Models ,Compliance in Cloud, Multi- TenantSecurityintheCloud,SecureCloudArchitecture, Cloud Security Best Practices | Students will be able to understand and analyzesecurity issues. (BTL 1- Understand, BTL 4- Analyze). |
10 | Unit 10: Privacy and Compliance in Cloud Computing- Privacy Concerns in Cloud Computing, Data Privacy Regulations, Secure Data Storage and
TransferinCloud,RiskManagementinCloud Environments. |
Students will be able to remember Privacy Concerns.(BTL 2- Remember) |
11 | Unit 11: Cloud Computing for Mobile and IoTApplications-MobileCloudComputing,IoTand Cloud Integration,IoTCloudArchitecture,CloudServicesfor MobileDevices,SecurityandPrivacyforMobileCloud Applications. | Studentswillbeableto analyzeimportanceofIoT appsoncloud(BTL4- analyse). |
12 | Future Trends and Research in Cloud Computing-EmergingCloudComputingModels,AI and Machine Learning, Sustainability, CloudComputingin the Digital Transformation Era. | Students will be able toevaluate and analyze the use of Technology according future trends and research areas.(BTL 4- analyze, (BTL 5- evaluate). |
Textbooks:
1. “CloudComputing: Principles, Systemsand Applications” byNikosAntonopoulos,Lee Gillam 2. “CloudComputing:Concepts,Technology&Architecture”byThomasErl
ReferenceBooks:
1. “CloudComputing:AHands-OnApproach”byArshdeepBahga,VijayMadisetti 2. “Architecting theCloud: Design DecisionsforCloud Computing Service Models(SaaS, PaaS, and IaaS)” by Michael Kavis |
WirelessSensorNetworkandIOTSyllabus
CourseCode:LMC0342 | CourseTitle:WirelessSensorNetworkandIOT(3Credits) |
CourseLearningOutcomes
· Understand the fundamentals of Wireless Sensor Networks (WSN) and the Internet of Things (IoT). · AnalysethearchitectureandprotocolsusedinWSNandIoTsystems. · EvaluatevariouswirelesscommunicationtechnologiesusedinIoTandWSN. · Investigatethesecurity,privacy,andstandardsinWSNandIoT. · ExamineemergingtrendsandstandardsinWSNandIoT,including5GandIoTprotocols. |
|
*BTL-Bloom’sTaxonomyLevel.1-Understand,2-Remember,3-Apply,4-Analyze,5-
Evaluate,6-Create |
CourseContents
Sr.No | UnitNo./Unitdescription | UnitOutcome |
1 | Unit1:IntroductiontoWirelessSensorNetworksand IoT- Overview of Wireless Sensor Networks, Definition and ImportanceofIoT,ArchitectureofWSN,ComponentsofWSN: Sensors,Actuators,andNodes,IoTSystemArchitecture,Types of WSNs and IoT Networks, Applications of WSN and IoT | Students will be able to understand Wireless Sensor Networks(BTL1-
Understanding). |
2 | Unit2:WSNDesignPrinciplesandCommunicationModels- WSNDesignConstraints,TopologiesinWSN,Communication Models: Broadcast, Multicast, andUnicast,DataCommunication in WSN: Analog and Digital Transmission. | Students will be able to understand and remember models.(BTL 1-Understand, BTL 2- Remember). |
3 | Unit 3: IoT Protocols and Communication Technologies- IoT Protocol Stack: Application, Transport, Network, and Data LinkLayers, LowPower WAN, CommunicationTechnologies, Role of IP in IoT, Interoperability Issues in IoT. | Students will be able to understand and rememberIoT Protocols. (BTL 3- Apply). |
4 | Unit4:WSNRoutingProtocols-OverviewofWSNRouting Protocols, Proactive vs Reactive Routing, Flat and Hierarchical Routing Protocols, Data Aggregation and Routing in WSN, Energy-EfficientRoutingProtocols,MultipathRoutingProtocols, Sensor Network Mobility and its Impact on Routing | Students will be able to understand and remember Routing Protocols. (BTL 3- Apply). |
5 | Unit 5: IoT Data Management and Processing- Data Collection in IoT Systems, IoT Data Storage and Cloud Integration,BigDatainIoT,DataProcessingTechniquesinIoT, Real-time Data Analytics, Data Fusion and Integration
Techniques. |
Students will be able to use cloud cloud storage in IoT. (BTL 6-Create). |
6 | Unit 6: Security Challenges inWSN and IoT- Securityin WSN and IoT: Introduction and Challenges, Authentication and Access Control, Data Privacy and Integrity, Key Management Techniques in WSN, Security Protocols for IoT , Secure CommunicationinWSN,AttacksinWSNandIoTandMitigation | Students will be able analyze and evaluate Security in IoT. (BTL 4- analyze, BTL 5- Evaluate). |
Strategies | ||
7 | Unit 7: IoT Standards and Protocols- Standards for IoT, RoleofStandardsinIoTInteroperabilityIPv6andIoTStandards, Industry-SpecificIoTStandards(Healthcare,SmartCities),Open Standards vs Proprietary Standards | Students will be able analyze importance of IoT standards. (BTL 4- Analyze). |
8 | Unit 8: WSN and IoT Application Development- Application Design in WSN and IoT, Building Smart Systems: Smart Homes, Smart Cities ,IoT Application Development Platforms ,WSN-basedEnvironmental MonitoringSystems,IoT in Healthcare: Remote Monitoring, Wearables. | Students will be able to understand IoT Application. (BTL 1-Understand and BTL 2- Remember). |
9 | Unit 9: Energy Management in WSN and IoT-Energy- EfficiencyChallengesin WSN,PowerManagementTechniques in WSN, Low Power Operation in IoT Devices ,Energy HarvestinginIoT,Power-AwareRoutinginWSN,BatteryLife
OptimizationTechniques,Energy-EfficientIoTApplications |
Students will be able to analyze Energy management in IoT. (BTL 4- Analyze). |
10 | Unit10:EmergingTrendsinWSNandIoT-5GandIts Impact on IoT,Cloud and Fog Computing Integration with IoT,Artificial Intelligence and Machine Learning in IoT. | Students will be able to remember new Trends in WSNandIoT.(BTL2-
Remember) |
11 | Unit 11: IoT in Industry 4.0Industry 4.0 Concepts and IoT,Smart Manufacturingand IoT,IoT inIndustrialAutomation, Cyber-PhysicalSystemsandIoT,PredictiveMaintenanceusing IoT,Industrial IoTProtocols and Standards. | Students will be able toanalse IoT in industry.(BTL 4- analyse). |
12 | Unit 12: Future Directions in WSN and IoT Standards- Next-Generation IoT Architectures, Integration of IoT withAI andBigData,AutonomousSystemsandIoT,TheRoleof5Gin IoT Evolution. | Students will be able to evaluate and use the Technology according to future trends. |
Textbooks:
1. “WirelessSensorNetworks:PrinciplesandPractice”byKazemSohraby,DanielMinoli,Taieb Znati 2. “Internetof Things: AHands-OnApproach”byArshdeepBahga, VijayMadisetti
ReferenceBooks:
1. “InternetofThings:FromResearchandInnovationtoMarketDeployment”byOvidiu Vermesan, Peter Friess 2. “WirelessSensor Networks: Technology, Protocols, andApplications”byIan F. Akyildiz,Mehmet Can Vuran |
Web Development (C#) Syllabus
Course Code: LMC0343 | Course Title:Web Development(C#) (3 Credits) |
Course Learning Outcomes · To gain the basic knowledge of Web Development
· The course focuses on Fundaments of OOPs in C# language.
· Understand static and dynamic webpages and implementing using HTML and C#. |
|
*BTL- Bloom’s Taxonomy Level. 1- Understand, 2- Remember, 3- Apply, 4- Analyze, 5- Evaluate, 6- Create |
Course Contents
Sr.No | Unit No./ Unit description | Unit Outcome |
1 | Unit 1- Introduction:Basic concept of Internet and Web, Internet Protocols, URL and Domain Names, Uses of Web | Students will be able to understand Web. (BTL 1-Understanding). |
2 | Unit 2-HTML: Document Type Definition, Web Page Template, HTML Element, Ordered List, Unordered List and Anchor Element. | Students will be able to understand and remember HTML. (BTL 1-Understand, BTL 2- Remember). |
3 | Unit 3-CSS: Overview of Cascading Style Sheet, Inline CSS, Embedded CSS, Using External Style sheet. | Students will be able apply CCS with HTML. (BTL 3- Apply). |
4 | Unit 4- Tables : Overview, Table rows, cells , Headers, Span Rows and Columns, Colspan, RowspanStyle a table with CSS, | Students will be able to use tables in HTML. (BTL3-Apply). |
5 | Unit 5-Forms: Form Elements, Form Controls, Input Element form Control, Scrolling Text Box, Style a form with CSS. | Students will be able to create forms in HTML. (BTL 6-Create). |
6 | Unit 6-Search Engine Optimization: Popular SearchEngines, Search Engine Optimization, Role of Keywords, Tags in SEO, Monitoring Search engine | Students will be able analyze importance of SEO in Web Development. (BTL 4- analyze, BTL 5-Evaluate). |
7 | Unit 7- C# and .NET – Developing C# Applications within Visual Studio .Net, Basics of C# and .NET. | Students will be able analyze importance of C# and .NET in Web Development.(BTL 4- Analyze). |
8 | Unit 8-C# Foundation – Basics of C#, Features of C#, Keywords, variables in C#, data types in C#, operators in C#,. | Students will be able to understand and remember C# Basics. (BTL 1-Understand andBTL 2- Remember). |
9 | Unit 9– Control Statements and Loops – If, switch statement, fort loop, While loop, do while, break and continue. | Students will be able to analyze the working of loops and control statements. (BTL 4- Analyze). |
10 | Unit 10-Functions and Arrays: Functions in C#, Access specifiers, Call by value, Call by reference, Arrays in C#. | Students will be able to create functions and arrays.(BTL6- Create) |
11 | Unit 11-Object Oriented Programming: OOPs concepts, Classes, Class members, Constructors, Objects, Inheritance in C#, Derived Class, Base Class. | Students will be able to create C# programs with OOPs. (BTL 6-Create). |
12 | Unit 12-Methods: Creating Methods in detail, Calling a method, Parameters and Arguments in detail with example. | Students will be able to create C# programs with methods. (BTL 6-Create). |
Text book References: –
1. Web Development and Design Foundations with HTML5 Terry Ann Felke-Morris Pearson publication 2. C# Tips and Techniques OtherReferences: 1. Web Technologies – UttamK.Roy – Oxford Publication. 2. Web Technologies – Black Book – Kogent Learning Solutions Inc. |