w3resource

R Programming: Drop Rows by number from a given Data Frame


Write a R program to drop row(s) by number from a given data frame.

Sample Solution :

R Programming Code :

# Create a data frame named exam_data with four columns: name, score, attempts, and qualify
exam_data = data.frame(
  name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'),
  score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19),
  attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1),
  qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes')
)

# Print a message indicating that the following output is the original data frame
print("Original dataframe:")

# Print the contents of the exam_data data frame
print(exam_data)

# Remove rows 2, 4, and 6 from the exam_data data frame and update exam_data with the remaining rows
exam_data <- exam_data[-c(2, 4, 6), ]

# Print the data frame after removing specified rows
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
        name score attempts qualify
1  Anastasia  12.5        1     yes
3  Katherine  16.5        2     yes
5      Emily   9.0        2      no
7    Matthew  14.5        1     yes
8      Laura  13.5        1      no
9      Kevin   8.0        2      no
10     Jonas  19.0        1     yes                         

Explanation:

  • Create Data Frame:
    • Purpose: Creates a data frame named exam_data with columns name, score, attempts, and qualify.
    • Details: Each column is populated with a vector of values representing student attributes.
  • Print Original Data Frame:
    • Purpose: Displays the message "Original dataframe:" and then prints the exam_data data frame.
    • Details: Shows the contents of exam_data before any modifications.
  • Remove Specific Rows:
    • Purpose: Removes rows 2, 4, and 6 from the exam_data data frame.
    • Details: Uses negative indexing to exclude these rows, and the updated data frame is saved back to exam_data.
  • Print Updated Data Frame:
    • Purpose: Displays the updated exam_data data frame after row removal.
    • Details: Shows the data frame with the specified rows removed.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to drop column(s) by name from a given data frame.
Next: Write a R program to sort a given data frame by multiple column(s).

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.