Find below a solution using data.table
. This version might be especially useful if your key
variable (here a
) is not numeric.
# Set up data
a <- c(98:103, 998:1003)
b <- 1:length(a)
# Set of values to look for
A <- 1:99
B <- 100:999
# Create data table and set key
DT <- data.table(a,b)
setkey(DT, a)
# Add new variable
DT[J(A), c:="a"]
DT[J(B), c:="b"]
DT[is.na(DT$c), c:="c"]
If your key variable is not numeric, you can change DT[J(A), c:="a"]
to DT[A,c:="a"]
.