1. Introduction
This R program shows how to store data in a data frame and perform various operations on it. A data frame is a key data structure in R for storing datasets in a tabular format, similar to a spreadsheet or a database table.
2. Program Steps
1. Create a data frame.
2. Add a new column to the data frame.
3. Modify an existing column in the data frame.
4. Remove a column from the data frame.
5. Access a specific row of the data frame.
6. Print the final data frame after all operations.
3. Code Program
# Step 1: Create a data frame
data_df <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35), Gender = c("Female", "Male", "Male"))
# Step 2: Add a new column (Salary)
data_df$Salary <- c(50000, 60000, 55000)
# Step 3: Modify an existing column (Age)
data_df$Age <- data_df$Age + 5
# Step 4: Remove a column (Gender)
data_df$Gender <- NULL
# Step 5: Access a specific row (Row 2)
accessed_row <- data_df[2, ]
# Step 6: Print the final data frame
print("Final Data Frame after operations:")
print(data_df)
Output:
Final Data Frame after operations: Name Age Salary 1 Alice 30 50000 2 Bob 35 60000 3 Charlie 40 55000
Explanation:
1. data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 35), Gender = c("Female", "Male", "Male")): Creates a data frame with three columns: Name, Age, and Gender.
2. data_df$Salary <- c(50000, 60000, 55000): Adds a new column 'Salary' to the data frame.
3. data_df$Age <- data_df$Age + 5: Modifies the 'Age' column by incrementing each value by 5.
4. data_df$Gender <- NULL: Removes the 'Gender' column from the data frame.
5. data_df[2, ]: Accesses the second row of the data frame.
6. print("Final Data Frame after operations:"), print(data_df): Prints the final data frame after performing all operations.
Comments
Post a Comment