Browse Source

Adding remapVariable

Andrej 1 week ago
parent
commit
1f027fa57b
3 changed files with 61 additions and 0 deletions
  1. 1 0
      NAMESPACE
  2. 34 0
      R/modifyData.R
  3. 26 0
      man/remapVariable.Rd

+ 1 - 0
NAMESPACE

@@ -1,4 +1,5 @@
 # Generated by roxygen2: do not edit by hand
 
+export(remapVariable)
 export(selectValid)
 export(sumWithNA)

+ 34 - 0
R/modifyData.R

@@ -51,3 +51,37 @@ selectValid<-function(df,cutoff=2,timeVar='years_to_event',osVar='st_osMAP',targ
    df
 
 }
+
+
+#' Remap/change value of variable according to a lookup table
+#'
+#' @param df data frame
+#' @param origVar name of original variable
+#' @param mapVar name of variable with updated values
+#' @param valueMap mapping of variables from old to new, named list 
+#' where names() are values to be found in data frame and values() contain new values
+#' @param num ensure output value is numeric 
+#' 
+#' @return data frame with updated column
+#' @export
+
+remapVariable <- function(df, origVar, mapVar, valueMap, num=TRUE) {
+    if (!origVar %in% colnames(df)) {
+        base::stop(base::sprintf("Variable '%s' not found in data frame", origVar))
+    }
+    if (num){
+       # Ensures output type consistency
+       df[[mapVar]] <- base::vapply(base::as.character(df[[origVar]]), getNewValue, map=valueMap,FUN.VALUE = numeric(1)) 
+    }
+    else 
+       df[[mapVar]] <- base::sapply(df[[origVar]], getNewValue, map=valueMap)
+    
+    df
+}
+
+getNewValue<-function(x,map){
+   if (x %in% base::names(map))
+      map[[x]]
+   else 
+      NA
+}

+ 26 - 0
man/remapVariable.Rd

@@ -0,0 +1,26 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/modifyData.R
+\name{remapVariable}
+\alias{remapVariable}
+\title{Remap/change value of variable according to a lookup table}
+\usage{
+remapVariable(df, origVar, mapVar, valueMap, num = TRUE)
+}
+\arguments{
+\item{df}{data frame}
+
+\item{origVar}{name of original variable}
+
+\item{mapVar}{name of variable with updated values}
+
+\item{valueMap}{mapping of variables from old to new, named list
+where names() are values to be found in data frame and values() contain new values}
+
+\item{num}{ensure output value is numeric}
+}
+\value{
+data frame with updated column
+}
+\description{
+Remap/change value of variable according to a lookup table
+}