Is there a way to add new columns to a data.frame and populate them with NAs (to be filled by a later function), where the titles of the new column come from a vector of characters (strings).
Example:
What I'd like to do is add some new columns based on the subject column of this data.frame
exam_results <- data.frame(
subject = c("maths", "economics", "chemistry"),
final_score = c(70, 78, 61),
midterm_score = c(53, 66,40)
)
i.e:
# new object for new df
exam_results_new_columns <- exam_results
# get the names of the different subjects
subjects <- unique(exam_results$subject)
column_names <- c()
for (i in 1:length(subjects)) {
column_names[i] <- paste0("subject_", subjects[i])
exam_results_new_columns$i <- NA
}
This will produce the following df:
subject | final_score | midterm_score | i |
---|---|---|---|
maths | 70 | 53 | NA |
economics | 78 | 66 | NA |
chemistry | 61 | 40 | NA |
but what I would like is:
subject | final_score | midterm_score | subject_economics | subject_chemistry |
---|---|---|---|---|
maths | 70 | 53 | NA | NA |
economics | 78 | 66 | NA | NA |
chemistry | 61 | 40 | NA | NA |
is there a way I can achieve this?