[R] primitives again

Berwin A Turlach berwin at maths.uwa.edu.au
Mon Mar 16 03:04:34 CET 2009


On Sun, 15 Mar 2009 14:23:40 +0100
Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:

> Edna Bell wrote:
> > How do I find the functions which are primitives, please?
> >   
> 
> you can scan the whole search path for functions that are primitives:
> 
>     primitives = sapply(search(), function(path)
>      with(as.environment(path), Filter(is.primitive, lapply(ls(),
> get))))
> 
> primitives is a list of named lists of primitives, one sublist for
> each attached package (most sublists will be empty, i guess).

The code above will miss some primitives in package:base, namely those
that start with a dot:

R> primitives <- sapply(search(), function(path)
+       with(as.environment(path), 
+            Filter(is.primitive, lapply(ls(), get))))
R> sapply(primitives, length)
       .GlobalEnv     package:stats  package:graphics package:grDevices 
                0                 0                 0                 0 
    package:utils  package:datasets   package:methods         Autoloads 
                0                 0                 2                 0 
     package:base 
              176 
R> primitives <- sapply(search(), function(path)
+       with(as.environment(path), 
+            Filter(is.primitive, lapply(ls(all=TRUE), get))))
R> sapply(primitives, length)
       .GlobalEnv     package:stats  package:graphics package:grDevices 
                0                 0                 0                 0 
    package:utils  package:datasets   package:methods         Autoloads 
                0                 0                 2                 0 
     package:base 
              188 

Also, but that is a matter of taste, it could be preferable to use
sapply instead of lapply:

R> primitives$`package:methods`
[[1]]
function (expr)  .Primitive("quote")

[[2]]
.Primitive("[[<-")

R> head(primitives$`package:base`)
[[1]]
function (x)  .Primitive("!")

[[2]]
function (e1, e2)  .Primitive("!=")

[[3]]
.Primitive("$")

[[4]]
.Primitive("$<-")

[[5]]
function (e1, e2)  .Primitive("%%")

[[6]]
function (x, y)  .Primitive("%*%")

R> primitives <- sapply(search(), function(path)
+        with(as.environment(path), 
+             Filter(is.primitive, sapply(ls(all=TRUE), get))))
R> primitives$`package:methods`
$Quote
function (expr)  .Primitive("quote")

$`el<-`
.Primitive("[[<-")

R> head(primitives$`package:base`)
$`!`
function (x)  .Primitive("!")

$`!=`
function (e1, e2)  .Primitive("!=")

$`$`
.Primitive("$")

$`$<-`
.Primitive("$<-")

$`%%`
function (e1, e2)  .Primitive("%%")

$`%*%`
function (x, y)  .Primitive("%*%")


Cheers,

	Berwin




More information about the R-help mailing list