在RStudio中对比两列字母成绩生成Finalgrade列求助
Hey there! Let's figure out how to create that Finalgrade column for your student grades. Since letter grades don't have a built-in "rank" in R, we first need to tell R exactly which grades are better than others. Here's how to do it easily, whether you prefer using the tidyverse (dplyr) or base R:
Using dplyr (Tidyverse)
This method is super readable, which is great for beginners. First, we'll convert your letter grade columns into ordered factors—this lets R understand the hierarchy of grades.
- First, install and load dplyr if you haven't already:
install.packages("dplyr") library(dplyr)
- Define your grade hierarchy (adjust this to match your actual grading scale—put the highest grade first!):
# Example hierarchy: tweak this to fit your school's grading system grade_order <- c("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "F")
- Transform your data to create the
Finalgradecolumn:
# Replace `student_grades` with your actual data frame name # Replace `Grade1` and `Grade2` with your two letter grade column names student_grades <- student_grades %>% # Convert grade columns to ordered factors so R can compare their ranks mutate( Grade1_fct = factor(Grade1, levels = grade_order, ordered = TRUE), Grade2_fct = factor(Grade2, levels = grade_order, ordered = TRUE) ) %>% # Pick the higher grade (smaller factor value = better grade, since we ordered from highest to lowest) mutate(Finalgrade = case_when( Grade1_fct < Grade2_fct ~ Grade1, # Grade1 is the better grade Grade2_fct < Grade1_fct ~ Grade2, # Grade2 is the better grade TRUE ~ Grade1 # If grades are equal, just pick either (we chose Grade1 here) )) %>% # Optional: Clean up by removing the temporary factor columns select(-Grade1_fct, -Grade2_fct)
Using Base R
If you prefer not to use extra packages, here's a base R approach using match() to assign rank values to each grade:
- Define your grade hierarchy (same as above):
grade_order <- c("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "F")
- Calculate rank values for each grade and pick the higher one:
# Replace `student_grades`, `Grade1`, and `Grade2` with your actual names student_grades$Grade1_rank <- match(student_grades$Grade1, grade_order) student_grades$Grade2_rank <- match(student_grades$Grade2, grade_order) # Assign the better grade to Finalgrade student_grades$Finalgrade <- ifelse( student_grades$Grade1_rank < student_grades$Grade2_rank, student_grades$Grade1, ifelse( student_grades$Grade2_rank < student_grades$Grade1_rank, student_grades$Grade2, student_grades$Grade1 ) ) # Optional: Remove the temporary rank columns student_grades <- student_grades[, !names(student_grades) %in% c("Grade1_rank", "Grade2_rank")]
Quick Tip
Make sure your grade_order vector matches your actual grading scale! For example, if your school uses a simpler scale without "+/-" grades, just adjust the vector to c("A", "B", "C", "D", "F").
内容的提问来源于stack exchange,提问作者fjinnnnn

