mapply                 package:base                 R Documentation

_A_p_p_l_y _a _f_u_n_c_t_i_o_n _t_o _m_u_l_t_i_p_l_e _l_i_s_t _o_r _v_e_c_t_o_r _a_r_g_u_m_e_n_t_s

_D_e_s_c_r_i_p_t_i_o_n:

     'mapply' is a multivariate version of 'sapply'. 'mapply' applies
     'FUN' to the first elements of each ... argument, the second
     elements, the third elements, and so on. Arguments are recycled if
     necessary. 

     'Vectorize' returns a new function that acts as if 'mapply' was
     called.

_U_s_a_g_e:

     mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,
           USE.NAMES = TRUE)

     Vectorize(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE,
               USE.NAMES = TRUE)

_A_r_g_u_m_e_n_t_s:

     FUN: Function to apply, found via 'match.fun'.

     ...: Arguments to vectorise over (list or vector).

MoreArgs: A list of other arguments to 'FUN'.

SIMPLIFY: Attempt to reduce the result to a vector or matrix?

USE.NAMES: If the first ... argument is character and the result does
          not already have names, use it as the names.

vectorize.args: A character vector of arguments which should be
          vectorized.  Defaults to all arguments to 'FUN'.

_D_e_t_a_i_l_s:

     The arguments named in the 'vectorize.args' argument to
     'Vectorize' correspond to the arguments passed in the '...' list
     to 'mapply'.  However, only those that are actually passed will be
     vectorized; default values will not. See the example below.

_V_a_l_u_e:

     'mapply' returns a list, vector, or matrix.

     'Vectorize' returns a function with the same arguments as 'FUN',
     but wrapping a call to 'mapply'.

_S_e_e _A_l_s_o:

     'sapply', 'outer'

_E_x_a_m_p_l_e_s:

     mapply(rep, 1:4, 4:1)

     mapply(rep, times=1:4, x=4:1)

     mapply(rep, times=1:4, MoreArgs=list(x=42))

     # Repeat the same using Vectorize
     vrep <- Vectorize(rep)
     vrep(1:4, 4:1)
     vrep(times=1:4, x=4:1)

     vrep <- Vectorize(rep, "times")
     vrep(times=1:4, x=42)

     f <- function(x=1:3, y) c(x,y)
     vf <- Vectorize(f, SIMPLIFY = FALSE)
     f(1:3,1:3)
     vf(1:3,1:3)
     vf(y=1:3) # Only vectorizes y, not x

     # Nonlinear regression contour plot, based on nls() example

     SS <- function(Vm, K, resp, conc) {
         pred <- (Vm * conc)/(K + conc)
         sum((resp - pred)^2 / pred)
     }
     vSS <- Vectorize(SS, c("Vm", "K"))
     Treated <- subset(Puromycin, state == "treated")

     Vm <- seq(140, 310, len=50)
     K <- seq(0, 0.15, len=40)
     SSvals <- outer(Vm, K, vSS, Treated$rate, Treated$conc)
     contour(Vm, K, SSvals, levels=(1:10)^2, xlab="Vm", ylab="K")

