R Value Mapping with a Vector

384 views Asked by At

I'm looking for a function similar to FindReplace that will allow me to map values based on a vector, rather than a single value.

I have a lookup table that looks like this that I want to use to map values in a dataframe.

Headers: COLUMN_NAME, CODE, DESCRIPTION
Row1: arrmin, 97, Officially Cancelled
Row2: arrmin, 98, Unknown if Arrived
Row3: atmcond, -1, Blank
Row4: atmcond, 0, No Additional Atmospheric Conditions

This lookup table has thousands of rows, so I can't type them in manually, and my original solution is too inefficient and will take days to run.

The dataframe I am using has hundreds of columns, such as arrmin and atmcond that needs the values changed from 97 to Officially Cancelled, etc.

The values from 0-100 (or however many values there are) change based on which column it is in. I've written this code below, but it is really inefficient and takes days to run for 300k rows.

columnsToReplace <- which(colnames(CRASH) %in% CapitalColumns)
dfColumns <- colnames(CRASH)
for (i in columnsToReplace){
  tempColumn <- dfColumns[i]
  tempLookup <- capitalLookupTable[which(capitalLookupTable$COLUMN_NAME ==tempColumn),]
  CRASH <- FindReplace(data=CRASH,Var=tempColumn,replaceData = capitalLookupTable,
           from = "Code",to = "Description",exact=T)
}

columnsToReplace is a vector I created that contains the string names of each of the columns that exist in the lookup table.

1

There are 1 answers

0
Jean On
#Some data
s<-data.frame(A=c(1,1,2,2),B=c(2,4,6,6),C=c(1,3,5,7))
mapping<-data.frame(ColumnName=c(rep("A",2), rep("B",3), rep("C",4)), Code=c(1,2,2,4,6,1,3,5,7))
mapping$Description<-paste0(mapping$ColumnName, mapping$Code)

#From wide to long
library(reshape)
melted.s<-melt(s)

#Join
melted.s<-merge(melted.s, mapping, by.x=c("variable","value"), by.y=c("ColumnName","Code"))

#From long to wide
p<-data.frame(matrix(melted.s$Description, ncol=ncol(s)))
names(p)<-names(s)