Use mapply with different vector lengths

Hello,
When running the code below, the error "longer argument not a multiple of length of shorter" appears.
Would it be possible to apply my function to all the combinations of each element from each vector, even if these are not the same length? In my example below I should get 24 elements (432) in the resulting vector.
Thank you for your help!

a <- c(0,1,2,3)
p <- c(1,2,3)
M <- c(1,23)

calc_mass <- function(a,p,M)
{
  mass <- (a*M)/p
  return(mass)
}
masses_apply <- mapply(calc_mass,a,p,M)

You can use expand.grid to make all the combinations of the three vectors.

a <- c(0,1,2,3)
p <- c(1,2,3)
M <- c(1,23)

calc_mass <- function(a,p,M)
{
  mass <- (a*M)/p
  return(mass)
}

FullGrid <- expand.grid(a,p,M)
colnames(FullGrid) <- c("a","p","M")
nrow(FullGrid)
#> [1] 24
masses_apply <- mapply(calc_mass, FullGrid$a, FullGrid$p, FullGrid$M)

Created on 2023-08-12 with reprex v2.0.2

1 Like

This topic was automatically closed 7 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.