You can solve the problem you are describing using a matrix and a standard subset of R, without any if
m <- matrix(1:9, nrow=3, byrow=TRUE) m [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9
This means that you can index m using a subset of the matrix:
m[3, 2] [1] 8 m[3,3] [1] 9 m[2,3] [1] 6
And now you can apply this to your data:
df <- structure(list(V1 = c(3L, 3L, 3L, 3L, 3L, 3L, 2L, 1L, 2L, 3L), V2 = c(3L, 2L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -10L)) #df$m <- sapply(seq_len(nrow(df)), function(i)m[df$V1[i], df$V2[i]]) df$m <- m[as.matrix(df)] # Use matrix subsetting, suggested by @Aaron df V1 V2 m 1 3 3 9 2 3 2 8 3 3 3 9 4 3 3 9 5 3 3 9 6 3 3 9 7 2 3 6 8 1 2 2 9 2 2 5 10 3 3 9