1) switch Using DF
shown reproducibly in the Note at the end try using switch
as shown here. No packages are used.
transform(DF, Var3 = Var1 * sapply(Var2, switch, 30, 4, 1))
giving:
Var1 Var2 Var3
1 4 2 16
2 6 2 24
3 5 1 150
4 3 3 3
5 2 1 60
See ?switch
for more information.
2) arithmetic Another approach is to use an arithmetic statement that evaluates to the desired value. This also uses no packages.
transform(DF, Var3 = Var1 * ((Var2 == 1) * 30 + (Var2 == 2) * 4 + (Var2 == 3) * 1))
2a) A variation of this is:
transform(DF, Var3 = Var1 * outer(Var2, 1:3, "==") %*% c(30, 4, 1))
3) subscripting This also works:
transform(DF, Var3 = Var1 * c(30, 4, 1)[Var2])
4) factor Another approach is to create a factor and then convert that back to numeric:
transform(DF, Var3 = Var1 * as.numeric(as.character(factor(Var2, labels = c(30, 4, 1)))))
Note
Lines <- "Var1 Var2
4 2
6 2
5 1
3 3
2 1"
DF <- read.table(text = Lines, header = TRUE)