Two Functions with Same Name in Different Packages in R (Example)

 

In this R tutorial you’ll learn how to specify the package from which a function should be taken.

The tutorial consists of the following information:

Let’s do this…

 

Creation of Example Data

Have a look at the following example data:

data <- data.frame(x = 1:5,         # Create example data
                   y = 3:7)
data                                # Print example data
#   x y
# 1 1 3
# 2 2 4
# 3 3 5
# 4 4 6
# 5 5 7

The previous output of the RStudio console shows the structure of our example data: It contains two numeric columns both ranging from 1 to 5.

 

Example: Loading Multiple Packages with Same Function Names

The following code shows how to specify the package you want to use when applying a function. For the illustration in this example, we are using the plyr and Hmisc add-on packages. First, we have to install and load the plyr package:

install.packages("plyr")            # Install & load plyr
library("plyr")

The plyr package contains a function with name summarize(). We can apply the function as shown below:

summarize(data, z = x + y)          # Apply summarize function
#    z
# 1  4
# 2  6
# 3  8
# 4 10
# 5 12

Now, let’s also install and load the Hmisc add-on package:

install.packages("Hmisc")           # Install & load Hmisc
library("Hmisc")

If we try to run exactly the same code for the summarize function as before, the RStudio console returns an error:

summarize(data, z = x + y)          # Apply summarize function
# Error in summarize(data, z = x + y) : 
#   argument "by" is missing, with no default

The reason: Hmisc also contains a function with the name summarize(). Since we have loaded the Hmisc package after the plyr package, the summarize function of Hmisc overwrites the summarize function of the plyr package. In technical terms: The summarize function of plyr is “masked”.

Fortunately, the solution for this problem is quite simple. We just need to specify the package name before the application of a function:

plyr::summarize(data, z = x + y)    # Specify package
#    z
# 1  4
# 2  6
# 3  8
# 4 10
# 5 12

As you can see, the summarize function works as in the beginning.

 

Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which explains the contents of this article. You can find the video below.

 

The YouTube video will be added soon.

 

Furthermore, you might read the other articles on this website.

 

Summary: In this R tutorial you learned how to handle functions with the same name coming from different add-on packages. Let me know in the comments section, if you have further questions.

 



Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top