# Create a sample data frame
data <- data.frame(
Name = c("Alice", "Bob", "Charlie", "David", "Eve"),
Age = c(25, 30, 35, 28, 22),
Salary = c(50000, 60000, 75000, 52000, 48000)
)
# Display the entire data frame
cat("Original Data Frame:\n")
print(data)
# Indexing and Subsetting Data Frames
# Select rows where Age is greater than 28
selected_data <- data[data$Age > 28, ]
cat("\nSelected Data (Age > 28):\n")
print(selected_data)
# Select rows where Name is "Alice" or "David"
selected_data <- data[data$Name %in% c("Alice", "David"), ]
cat("\nSelected Data (Name is Alice or David):\n")
print(selected_data)
# Select Name and Salary columns
selected_data <- data[, c("Name", "Salary")]
cat("\nSelected Data (Name and Salary):\n")
print(selected_data)
# Manipulating and Analyzing Data
# Calculate the mean salary
mean_salary <- mean(data$Salary)
cat("\nMean Salary: ", mean_salary, "\n")
# Calculate the maximum age
max_age <- max(data$Age)
cat("Maximum Age: ", max_age, "\n")
# Add a new column with Salary divided by 12 (monthly salary)
data$MonthlySalary <- data$Salary / 12
cat("\nData Frame with Monthly Salary:\n")
print(data)
# Sort the data frame by Age in descending order
sorted_data <- data[order(-data$Age), ]
cat("\nData Frame Sorted by Age (Descending):\n")
print(sorted_data)