Use a lookup table if it's categorical:
> df = data.frame(x=1:5, y=letters[1:5])
> df
x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
> z=c("a", "c", "d")
The slow nested way:
> ifelse(z == "a", 1, ifelse(z=="b", 2, ifelse(z=="c", 3, ifelse(z=="d", 4,ifelse(z=="e", 5, NA)))))
[1] 1 3 4
The faster R way:
> df$x[sapply(z, function(x) which(x==df$y))]
[1] 1 3 4
If it's numeric, you can use cut
instead:
> z = c(1.1, 2.23)
> df$y[cut(z, df$x)]
[1] a b
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…