# Set up input values A <- c(1,3,2,4,5,3,4,2,1) # R doesn't like numbers as keys, so explicitly make them strings B <- list("1"=2,"2"=1,"3"=4,"4"=2,"5"=3) # Create result vector, using R's vector arithmetic # Have to cast A to a character vector # Usual list indexing doesn't quite work here, so use a method that creates a list then turn that list into a vector using as.numeric() result <- (A/as.numeric((B[as.character(A)])))^2 # Use R's selective replacement into an array to handle special case result[result<1] <- 0 print(result) # output: # [1] 0.000000 0.000000 4.000000 4.000000 2.777778 0.000000 4.000000 4.000000 # [9] 0.000000