What are double colons (: :) in R?

I follow a tutorial at Rbloggers and found the use of double colons, I looked online, but I could not find an explanation for their use. Here is an example of their use.

df <- dplyr::data_frame( year = c(2015, NA, NA, NA), trt = c("A", NA, "B", NA) ) 

I understand that it creates a data frame, but I do not understand their purpose.

+5
source share
2 answers

As you probably looked at the help page, now using :: helps to access the exact function from this particular package. When you download dplyr , you probably got the message as follows.

 The following objects are masked from 'package:base': intersect, setdiff, setequal, union 

So, for example, if you want to use the intersect function from dplyr or the base package, you need to specify using double colons :: . Usage will be as follows

 mtcars$model <- rownames(mtcars) first <- mtcars[1:20, ] second <- mtcars[10:20, ] dplyr::intersect(first, second) base::intersect(first, second) 

Update: added additional explanation

Note. The library loading sequence determines the preferred access to certain functions. Developers from different packages use the same function names. However, when R encounters a function, it passes through different libraries that a particular session has loaded in a sequential manner. You can check packages in a session by running (.packages())

  [1] "tidyr" "data.table" "dplyr" "stats" [5] "graphics" "grDevices" "utils" "datasets" [9] "methods" "base" 

As you can see in my example above, tidyr is the last library I loaded, which is the first r session entry. So, when you use a function in your code, first look for it in tidyr → then data.table → then dplyr , etc. Finally, the base package is looked through. Thus, in this process, when there is a coincidence of function names between packages, this is the one that loads the last masks of the previous ones. To avoid this disguise, you indicate in the R code where to look for the function. Therefore, here base::intersect will use the function from the base library instead of dplyr . In addition, you can use to avoid loading the full library. There are positive and negative sides to this. Read the links and find out more.

run and check the differences. Here are some resources for you to understand.

Compare library (), require (), ::

Namespace

+11
source

Several packages can have several functions with the same name. The double push operator allows you to specify the desired function:

 package::functionname 
+4
source

Source: https://habr.com/ru/post/1242435/


All Articles