`mapply()`

works with multivariate arrays, and applys a function to a set of vector or list arguments. `mapply()`

also simplifies the output.

Structure of the `mapply()`

function:

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

Answers to the exercises are available here.

**Exercise 1**

Beginning level

Required dataframe:

`PersonnelData <- data.frame(Representative=c(1:4),`

Sales=c(95,110,115,90), Territory=c(1:4))

Using `mapply()`

, find the classes of `PersonnelData`

‘s columns.

**Exercise 2**

Beginning level

Print “`PersonnelData`

” with the `mapply()`

function.

**Exercise 3**

Beginning level

Use `mapply()`

to inspect “`PersonnelData`

” for numeric values.

**Exercise 4**

Intermediate level

Use `mapply()`

to sum the vectors “`5:10`

” and “`20:25`

“.

**Exercise 5**

Intermediate level

Use `mapply()`

to paste the vector “`1:4`

” and “`5:8`

“, with the separator “`LETTERS[1:4]`

“.

**Exercise 6**

Intermediate level

Use `mapply()`

to paste “`PersonnelData$Representative`

“, “`PersonnelData$Sales`

“, and “`PersonnelData$Territory`

“, with the

“`MoreArgs=`

” argument of “`list(sep="-")`

“.

**Exercise 7**

Advanced level

Required variable:

`NewSales <- data.frame(Representative=c(1:4), Sales=c(104, 97, 112, 94), Territory=c(1:4))`

Sum the corresponding elements of `PersonnelData$Sales`

and `NewSales$Sales`

.

**Exercise 8**

Advanced level

Required function:

`merge.function <- function(x,y){return(x+y)}`

Use `merge.function`

to combine the `Sales`

totals from `PersonnelData`

and `NewSales`

.

**Exercise 9**

Advanced level

`mcmapply`

is a parallelized version of `mapply`

.

The structure of `mcmapply()`

is:

`mcmapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE, mc.preschedule = TRUE, mc.set.seed = TRUE, mc.silent = FALSE, mc.cores = getOption("mc.cores", 2L), mc.cleanup = TRUE)`

Required library:

`library(parallel)`

Use `mcmapply()`

to generate 5 lists of `1:5`

random numbers.

**Exercise 10**

Advanced level

Using `mcmapply()`

, create a 10 by 10 matrix with 10 rows of the sequence `1:10`

:

**What's next:**

- Explore all our (>1000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

## Leave a Reply