R/match_id.R

Defines functions match_id

match_id <- function(input, input_regex = "[^;]+",
                     ref, match, new, collapse = ";", ...) {
  # obtain the strings to match from input vector
  to_match <- regmatches(
    input,
    gregexpr(input_regex, input, ...)
  )

  # obtain list of matched values in appropriate order
  output_match <- lapply(to_match, function(x) match(x, ref[[match]]))

  # iterate over columns specified by new
  output_list <- lapply(new, function(x) Map("[",
                                             list(as.character(ref[[x]])),
                                             output_match))

  # # clean up output and convert to list of vectors
  if (!is.null(collapse)) {
    output_list <- lapply(output_list, lapply, paste, collapse = collapse)
  } else {output_list}

  output_list <- lapply(output_list, unlist)

  # give output list appropriate names

  if (length(output_list) == 1) {
    output <- unlist(output_list)
  } else {
    names(output_list) <- new
    output <- output_list
  }
  output
}
csdaw/csdata documentation built on April 23, 2020, 10:48 p.m.