Here's how to use a named vector to search:
Define test data:
dat <- data.frame( presult = c(rep("I", 4), "SS", "ZZ"), aresult = c("single", "double", "triple", "home run", "strikeout", "home run"), stringsAsFactors=FALSE )
Define a named number vector with estimates:
score <- c(single=1, double=2, triple=3, `home run`=4, strikeout=0)
Use vector indexing to compare results with results:
dat$base <- score[dat$aresult] dat presult aresult base 1 I single 1 2 I double 2 3 I triple 3 4 I home run 4 5 SS strikeout 0 6 ZZ home run 4
Additional Information:
If you do not want to create a named vector manually, say, in the case when you have large amounts of data, do it as follows:
scores <- c(1:4, 5) names(scores) <- c("single", "double", "triple", "home run", "strikeout")
(Or read the values โโand names from existing data. The goal is to build a numerical vector and then assign names.)
Andrie
source share