Reference counting is a mechanism to determine how many R objects are pointing to the same underlying SEXPREC (C structure of R objects). For example in
a <- 1:5
b <- a
a and b point to the same SEXPREC and if one of both is modified, the SEXPREC needs to be copied to not change the value of the other object. However, if the reference count of an object is not increased, this does not mean that it is not relevant for the computations. For example in
a <- 1:5
b <- a+1
a is relevant, but both a and b will have a low reference count because they are pointing to different SEXPREC. Hence, reference counting of R cannot be used to check if objects are created but never used.
Just for fun, one could use lexical scoping to count how many times an R object was access:
obj <- function(x){
n <- 0
get <- function() {n <<- n+1; x}
count <- function() n
list(get=get, count=count)
}
Then create a new R object with
a <- obj(1:10)
and access it with
a$get()
[1] 1 2 3 4 5 6 7 8 9 10
One can count how many times the object was accessed.
a$count()
[1] 1
max(a$get())
[1] 10
a$count()
[1] 2
If the object has count 0, it was created but never used.
b <- obj(2)
b$count()
[1] 0