R object identity

六月ゝ 毕业季﹏ 提交于 2019-12-17 19:36:28

问题


is there a way to test whether two objects are identical in the R language?

For clarity: I do not mean identical in the sense of the identical function, which compares objects based on certain properties like numerical values or logical values etc.

I am really interested in object identity, which for example could be tested using the is operator in the Python language.


回答1:


UPDATE: A more robust and faster implementation of address(x) (not using .Internal(inspect(x))) was added to data.table v1.8.9. From NEWS :

New function address() returns the address in RAM of its argument. Sometimes useful in determining whether a value has been copied or not by R, programatically.


There's probably a neater way but this seems to work.

address = function(x) substring(capture.output(.Internal(inspect(x)))[1],2,17)
x = 1
y = 1
z = x
identical(x,y)
# [1] TRUE
identical(x,z)
# [1] TRUE
address(x)==address(y)
# [1] FALSE
address(x)==address(z)
# [1] TRUE

You could modify it to work on 32bit by changing 17 to 9.




回答2:


You can use the pryr package.

For example, return the memory location of the mtcars object:

pryr::address(mtcars)

Then, for variables a and b, you can check:

address(a) == address(b)


来源:https://stackoverflow.com/questions/10912729/r-object-identity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!