Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how can I check if two variable names reference the same underlying object?

Tags:

For example:

A <- 1:10 B <- A 

Both A and B reference the same underlying vector.

Before I plow off and implement something in C... Is there a function in R which can test whether two variables reference the same underlying object?

Thanks.

like image 247
Zach Avatar asked Sep 06 '11 22:09

Zach


People also ask

How do I check if two variables are equal in R?

setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.

Can we create two variables using the same name in R?

It's not possible, an if statement has no special scope, so you can't have two variables with the same name within the same scope and access both, the latter will overwrite the former, so they should have different names.

Can two variables refer to the same object?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.


1 Answers

You can use the .Internal inspect function:

A <- 1:10 B <- A .Internal(inspect(A)) # @27c0cc8 13 INTSXP g0c4 [NAM(2)] (len=10, tl=0) 1,2,3,4,5,... .Internal(inspect(B))  # same # @27c0cc8 13 INTSXP g0c4 [NAM(2)] (len=10, tl=0) 1,2,3,4,5,... B[1] <- 21 .Internal(inspect(B))  # different # @25a7528 14 REALSXP g0c6 [NAM(1)] (len=10, tl=150994944) 21,2,3,4,5,... 

Simon Urbanek has written a simple package with similar functionality. It's called... wait for it... inspect. You can get it from R-forge.net by running:

install.packages('inspect',repos='http://www.rforge.net/') 

UPDATE: A word of warning:

I recommend you use Simon's package because I'm not going to recommend you call .Internal. It certainly isn't intended to be used interactively and it may very well be possible to crash your R session by using it carelessly.

like image 74
Joshua Ulrich Avatar answered Oct 20 '22 00:10

Joshua Ulrich