I would like to reshape the following data frame using dplyr::mutate(): The goal is to create a new column variable percent but ensuring that the values correspond to the correct subject. The data is currently in the "long" format. Detailed: I would like to extract rows pertaining the pattern "percentQ" and create a new column called percent based on each subject to ensure that the score aligns with the corresponding subject.
df_long <- structure(list(id = c(NA,NA, "scoreQ1", NA, "scoreQ2", NA, NA,"percentQ1", "percentQ2", NA, "GPA"),
subject = c(NA,NA, "Chris", NA, "Liz", NA, NA, "Chris","Liz", NA, NA),
grade = c(NA,NA, 45L, NA, 60L, NA, NA, 75L, 100L, NA)), row.names = c(NA,-11L), class = c("data.table", "data.frame"))
print(df_long)
#id subject grade
#<NA> <NA> NA
#<NA> <NA> NA
#scoreQ1 Chris 45
#<NA> <NA> NA
#scoreQ2 Liz 60
#<NA> <NA> NA
#<NA> <NA> NA
#percentQ1 Chris 75
#percentQ2 Liz 100
#<NA> <NA> NA
#GPA <NA> NA
Please suggest R scripts that would allow to reshape the data frame to the following:
As can be seen, the percent value corresponds to the correct subject, in this instance 75 for Chris and 100 for Liz. I have been running into issues, where I was unable to assign the percent values to the correct subject.
df_wide <- structure(list(id = c(NA,NA, "scoreQ1", NA, "scoreQ2", NA, NA, NA, "GPA"),
subject = c(NA,NA, "Chris", NA, "Liz", NA, NA, NA, NA),
grade = c(NA,NA, 45L, NA, 60L, NA, NA, NA, NA),
percent = c(NA,NA, 75L, NA, 100L, NA, NA, NA, NA)), row.names = c(NA,-9L), class = c("data.table", "data.frame"))
print(df_wide)
#id subject grade percent
#<NA> <NA> NA NA
#<NA> <NA> NA NA
#scoreQ1 Chris 45 75
#<NA> <NA> NA NA
#scoreQ2 Liz 60 100
#<NA> <NA> NA NA
#<NA> <NA> NA NA
#<NA> <NA> NA NA
#GPA <NA> NA NA