How to perform do.call in R

How to perform do.call in R, you may use the do.call() function to apply a certain function to an entire list.

The basic syntax used by this function is as follows:

do.call(function, list)

Use of do.call() in practise is demonstrated in the examples that follow.

Example 1: How to perform do.call in R with sum

The total of values in a list can be calculated using do.call() by using the following code:

#create list

mylist <- list(A=c(11, 12, 13), B=c(27, 25, 30), C=c(19, 19, 12))

#calculate sum of values in list

do.call(sum, mylist)
[1] 168

The sum of the values in the list is 168.

Data Analysis in R

Note that attempting to use sum() on the list directly would result in an error:

#let’s create list

mylist <- list(A=c(11, 12, 13), B=c(27, 25, 30), C=c(19, 19, 12))

#now attempt to sum values in list

sum(mylist)
Error in sum(mylist) : invalid 'type' (list) of argument

Example 2: Use do.call() with mean

The mean of values in a list may be calculated using do.call() by using the following code:

#let’s define argument to use in do.call

args <- list(10:20, na.rm=TRUE)

#calculate mean of values in list

do.call(mean, args)
[1] 15

The list’s values have a mean value of 15, which.

Note that attempting to use mean() on the list directly would result in an error:

#attempt to calculate mean of values in list

mean(list(10:20), na.rm=TRUE)
[1] NA
Warning message:
In mean.default(list(10:20), na.rm = TRUE) :  argument is not numeric or logical: returning NA

Example 3: Use do.call() with rbind

#we can create three data frames

df1 <- data.frame(team=c('A', 'B', 'C'),
                  points=c(2, 7, 3))
df2 <- data.frame(team=c('D', 'E', 'F'),
                  points=c(2, 1, 0))
df3 <- data.frame(team=c('G', 'H', 'I'),
                  points=c(1, 5, 4))

#now place the three data frames into list

df_list <- list(df1, df2, df3)

#row bind together all the three data frames

Free Data Science Books » EBooks »

do.call(rbind, df_list)
  team points
1    A      2
2    B      7
3    C      3
4    D      2
5    E      1
6    F      0
7    G      1
8    H      5
9    I      4

As a result, one data frame is created that includes the rows from all three data frames.

Note that if we attempted to use rbind() on the list directly, we would not get the correct data frame:

You may also like...

2 Responses

  1. Liana says:

    thanks for info

  2. How is the do.call function utilized in R, and what specific situations or problems does it address?

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × three =