When to use mapply() over sapply()

When and how to use mapply()

Use mapply() when you need to pass more than one (multiple) vector to sapply(). Take for example, the two vectors .url and .destfile which contain url download files and file destinations, respectively. We want to use download.file() to download the files in .url to the file destinations in .destfile. We can use:

mapply(download.file, url = .url, destfile = .destfile)

While download.file() does support vectorised operations using method = "libcurl", I (personally) find it more convenient to use the mapply() function. The mapply() function will also recycle elements in vectors if they are not of the same length. So for example, I could have declared the additional argument mode = "wb" and since that argument is just a vector of length one, it would have been recycled however many times is needed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s