R Programming: Drop column(s) by Name from a Given Data Frame
Write a R program to drop column(s) by name from a given data frame.
Sample Solution :
R Programming Code :
# Create a data frame named 'exam_data' with columns: name, score, attempts, qualify
exam_data = data.frame(
name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'), # Names of students
score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19), # Scores obtained by students
attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1), # Number of attempts made by students
qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes') # Qualification status of students
)
# Print the message "Original dataframe:"
print("Original dataframe:")
# Print the original data frame 'exam_data'
print(exam_data)
# Remove the columns 'name' and 'qualify' from 'exam_data' using subset function
exam_data = subset(exam_data, select = -c(name, qualify))
# Print the modified data frame after removing specified columns
print(exam_data)
Output:
[1] "Original dataframe:" name score attempts qualify 1 Anastasia 12.5 1 yes 2 Dima 9.0 3 no 3 Katherine 16.5 2 yes 4 James 12.0 3 no 5 Emily 9.0 2 no 6 Michael 20.0 3 yes 7 Matthew 14.5 1 yes 8 Laura 13.5 1 no 9 Kevin 8.0 2 no 10 Jonas 19.0 1 yes score attempts 1 12.5 1 2 9.0 3 3 16.5 2 4 12.0 3 5 9.0 2 6 20.0 3 7 14.5 1 8 13.5 1 9 8.0 2 10 19.0 1
Explanation:
- Create a data frame: A data frame named exam_data is created with four columns: name, score, attempts, and qualify.
- name: A vector of student names.
- score: A vector of scores obtained by the students.
- attempts: A vector indicating the number of attempts made by the students.
- qualify: A vector indicating the qualification status of the students (yes or no).
- Print message: Prints the message "Original dataframe:" to indicate that the original data frame will be displayed.
- Print the original data frame: Prints the exam_data data frame showing all columns (name, score, attempts, and qualify).
- Drop columns by name: Uses the subset() function to create a modified version of the exam_data data frame by removing the name and qualify columns.
- Print the modified data frame: Prints the modified exam_data data frame, which now only contains the score and attempts columns.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to add new row(s) to an existing data frame.
Next: Write a R program to drop row(s) by number from a given data frame.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics