1

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?

Ric S
  • 9,073
  • 3
  • 25
  • 51
dcurrie27
  • 319
  • 3
  • 14

1 Answers1

2

In the for cycle, use square brackets [] instead of the dollar sign $

subjects <- unique(exam_results$subject)
column_names <- paste0("subject_", subjects)

for(i in column_names)
  exam_results_new_columns[,i] <- NA

Output

#     subject final_score midterm_score subject_maths subject_economics subject_chemistry
# 1     maths          70            53            NA                NA                NA
# 2 economics          78            66            NA                NA                NA
# 3 chemistry          61            40            NA                NA                NA
Ric S
  • 9,073
  • 3
  • 25
  • 51