Nested loop with mapply

I am trying to understand the mapply function, but I don't get it. Lets suppose I want to multiply each element of a vector with each element of another vector like this:

a <- c(1,2)

b <- c(1,2,3)

for (i in a){
  for (j in b){
    print(i*j)
  }
}

Return 1 2 3 2 4 6, thats what I want.

func <- function(x,y){
  return (x*y)
}
mapply(func, a, b)

This however returns 1 4 3. Why does it not work?

mapply does not generate all the combinations of a and b. It simply applies over the vectors a and b, recycling them if necessary. So in your case a become c(1,2,1) to make it the same length as b. Read the documentation for mapply.

see https://stackoverflow.com/questions/33856920/apply-a-function-over-all-combinations-of-a-list-of-vectors-r
see https://stackoverflow.com/questions/53570566/apply-a-function-over-pairwise-combinations-of-arguments

another option for you

a <- c(1,2)
b <- c(1,2,3)
df1 <- expand.grid(b=b,a=a)
df1$c <- df1$a*df1$b
df1

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.