R: Changes to dataframe variables from void function do not save

Viewed 38

I have several variables in a dataframe that need to be updated. They all have the same prefix with a different suffix (see below), so I wrote a function to clean them all at once rather than go one-by-one. The function doesn't 'return' anything -- it only updates the specified variables in the dataframe. I am not sure I can specify a 'return' for this, since I am changing multiple variables (but not all of them) so I cannot 'return' the whole dataset nor any specific variable that is altered. From debugging, I can see that the variables all update within the function as expected, but after the function runs, the altered variables revert back to their previous values. Is there a way to make these changes to the dataset variables permanent?

# List of new variables for a data frame that will be updated    
screen$gender_man <- screen$gender_woman <- screen$gender_nonbin <- 
      screen$gender_trans <- screen$gender_addoption <- screen$gender_pnta <- NA

# Variable names for use within the function
    var_names <- as.character(expression(gender_man, gender_woman, gender_nonbin, 
      gender_trans, gender_addoption, gender_pnta))

# function designed to update newly created variables within dataframe
Multiple_CombQuest <- function(item_n, hcp_pre, chw_pre, name_vec) {
  for(i in 1:item_n) {
      hcp <- screen[,paste0(hcp_pre,i)]
      chw <- screen[,paste0(chw_pre,i)]
    
    combo <- ifelse(!is.na(hcp), hcp, chw)
    screen[,name_vec[i]] <- combo # sets the variables specified in line 1 to their new values
    
  }
print(screen$gender_man) # returns the updated version of the variable based on the above code (as expected)
}

Multiple_CombQuest(6, "Q23_", "Q55_", var_names)
print(screen$gender_man) # returns NA for all values rather than values updated in function (not expected)
0 Answers
Related