conv_fac <- function(
  dataset, # list containing input dataframes
  labels   # list of vectors; in each vector, first label is destination column and all the rest are sources
  ){
  for (i in seq_len(length(dataset))){
    this_df <- dataset[[i]]
    for (this_label in labels){
      col_target <- this_label[1]
      cols_source <- this_label[-1]
      vecs <- this_df[,cols_source]
      cat('\nProcessing dataframe #',i,': column ',col_target, ' from columns ', paste0(cols_source, collapse = ', '),  sep = '')      
      this_df[[col_target]] <- coalesce(!!!vecs) 
    }
    this_df -> dataset[[i]]
  }
  return(dataset)
}

# Usage:

ldat <- list("ALL" = df, "other" =df2) 
var1 <- c("Q9","Q8","Q4")
var2 <- c("Q7","Q6","Q5")

ldat2 <- conv_fac(dataset = ldat, labels = list(var1,var2))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top