R Programming - Reorder Columns in Data Frame by Column name
Write a R program to reorder an given data frame by column name.
Sample Solution:
R Programming Code:
# Create a data frame named 'exam_data' with 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 the original data frame
print("Original dataframe:")
# Print the contents of 'exam_data'
print(exam_data)
# Print a message indicating that columns will be reordered
print("Reorder by column name:")
# Reorder columns of 'exam_data' to the specified order
exam_data = exam_data[c("name", "attempts", "score", "qualify")]
# Print the reordered data frame
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 [1] "Reorder by column name:" name attempts score qualify 1 Anastasia 1 12.5 yes 2 Dima 3 9.0 no 3 Katherine 2 16.5 yes 4 James 3 12.0 no 5 Emily 2 9.0 no 6 Michael 3 20.0 yes 7 Matthew 1 14.5 yes 8 Laura 1 13.5 no 9 Kevin 2 8.0 no 10 Jonas 1 19.0 yes
Explanation:
- Create Data Frame:
- exam_data = data.frame(...)
- Creates a data frame named exam_data with four columns: name, score, attempts, and qualify.
- Each column is populated with a vector of values, representing student names, scores, number of attempts, and qualification status respectively.
- Print Original Data Frame:
- print("Original dataframe:")
- Prints a message indicating that the original data frame will be displayed.
- print(exam_data)
- Displays the contents of exam_data before any modifications.
- Print Reordering Message:
- print("Reorder by column name:")
- Prints a message indicating that the columns of the data frame will be reordered.
- Reorder Columns:
- exam_data = exam_data[c("name", "attempts", "score", "qualify")]
- Reorders the columns of exam_data according to the specified order: name, attempts, score, qualify.
- Print Reordered Data Frame:
- print(exam_data)
- Displays the contents of the data frame after the columns have been reordered.
Go to:
PREV : Write a R program to select some random rows from a given data frame.
NEXT :
Write a R program to compare two data frames to find the elements in first data frame that are not present in second data frame.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?