Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I'm learning R recently and confused by two function: lapply and do.call. It seems that they're just similar to map function in Lisp. But why are there two functions with such a different name? Why doesn't R just use a function called map?

1 Answer

0 votes
by
edited by

According to R Documentation:

lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X

Basic syntax:

lapply(X, FUN, …)

Where

X

a vector (atomic or list) or an expression object. Other objects (including classed objects) will be coerced by base::as.list

FUN

The function to be applied to each element of X. In the case of functions like +, %*%, the function name must be backquoted or quoted.

do.call

do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

Map

The map functions transform their input by applying a function to each element and 

returning a vector of the same length as the input.

Since Map is a wrapper around mapply, and lapply is a special case of mapply. Therefore Map and lapply show similarity in a lot of cases.

do.call is often used with rbind and cbind, as it is used to assemble lists into simpler structures. Its input is a function and it applies its other arguments to the function.

Examples:

For the data frame below:

df <- data.frame(names = c("SAM","ROB","MAX"), 

                  grade = rep(LETTERS[1:3]),

                  age = c(21,23,22), stringsAsFactors = FALSE)

 df

  names grade age

1   SAM     A  21

2   ROB     B  23

3   MAX     C  22

Output for lapply, Map, and do.call:

lapply(df, class)

$names

[1] "character"

$grade

[1] "character"

$age

[1] "numeric"

 Map(class, df)

$names

[1] "character"

$grade

[1] "character"

$age

[1] "numeric"

fun <- lapply(df, class)

do.call(cbind, fun) #takes a function as an input

     names       grade       age      

[1,] "character" "character" "numeric"

Browse Categories

...