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

前端 未结 3 938
抹茶落季
抹茶落季 2020-12-03 07:26

For example:

A <- 1:10
B <- A

Both A and B reference the same underlying vector.

Before I plow off and implement something in

3条回答
  •  误落风尘
    2020-12-03 07:59

    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.

提交回复
热议问题