Assignment: Data Mining and R Programming
1. Explain the steps to perform data preprocessing in R for a data mining
task.
Answer:
Data preprocessing is an essential step before applying data mining algorithms. The steps in R
are:
a. Import Data:
data <- [Link]("[Link]")
b. Handle Missing Values:
Check missing values:
sum([Link](data))
Replace missing values (e.g., with mean):
data$column[[Link](data$column)] <- mean(data$column, [Link] = TRUE)
c. Remove Duplicates:
data <- unique(data)
d. Data Transformation (e.g., normalization):
data$column <- scale(data$column)
e. Encoding categorical variables:
data$category <- [Link](data$category)
f. Feature Selection/Extraction:
Use correlation or other statistical methods to remove irrelevant features.
2. Discuss the steps involved in performing k-means clustering in R.
Answer:
a. Load and prepare the dataset:
data <- iris[, -5] # Removing label for clustering
b. Normalize the data:
data <- scale(data)
c. Apply k-means algorithm:
[Link](123)
kmeans_result <- kmeans(data, centers = 3)
d. Examine results:
kmeans_result$cluster
e. Visualize clusters:
library(ggplot2)
data_clustered <- [Link](data, cluster = kmeans_result$cluster)
ggplot(data_clustered, aes(x = data[,1], y = data[,2], color =
[Link](cluster))) +
geom_point()
3. Discuss the steps involved in performing k-means clustering in R.
Feature K-means Clustering Hierarchical Clustering
Type Partitional Hierarchical (agglomerative
or divisive)
Predefined clusters Must specify number of No need to specify;
clusters (k) dendrogram helps choose
Scalability Efficient for large datasets Slower for large datasets
Output Cluster assignments Dendrogram showing nested
clusters
Function in R kmeans() hclust() + cutree()
Distance Metric Uses Euclidean distance Allows various metrics
(Euclidean, Manhattan, etc.)
Visualization Basic or 2D plots Dendrogram
4 . How would you create a custom function in R? Provide an example.
Answer:
You can define a custom function in R using the function keyword.
Example:
# Custom function to calculate square of a number
square <- function(x) {
return(x^2)
# Calling the function
square(5)
# Output: 25
5. What are the different data types available in R, and how
can you check the data type of a variable?
Answer:
Common data types in R:
● Numeric: Decimal values (e.g., 3.14)
● Integer: Whole numbers (e.g., 5L)
● Character: Text (e.g., "Hello")
● Logical: Boolean (TRUE or FALSE)
● Complex: Complex numbers (e.g., 2 + 3i)
● Factor: Categorical variables
● Raw: Raw bytes
Check data type of a variable:
class(x) # returns class of the object
typeof(x) # returns the internal type
[Link](x)
[Link](x)
Example:
x <- "Hello"
class(x) # "character"
typeof(x) # "character"