R data.table weird value/reference semantics

后端 未结 3 706
野性不改
野性不改 2021-02-19 04:35

(This is a follow up question to this.)

Check this toy code:

> x <- data.frame(a = 1:2)
> foo <- function(z) { setDT(z) ; z[, b:=3:4] ; z } 
&g         


        
3条回答
  •  隐瞒了意图╮
    2021-02-19 05:16

    library(data.table)
    
    x <- data.frame(a = 1:2)
    y <- x                #y is a reference to x
    address(x)
    #[1] "0x55e07e31a1e8"
    address(y)
    #[1] "0x55e07e31a1e8"
    setDT(y)              #Add data.table to attr of y AND x, create a copy of it and let y point to it and make y a DT
    address(x)
    #[1] "0x55e07e31a1e8"
    address(y)
    #[1] "0x55e07e7b1300"
    class(x)
    #[1] "data.table" "data.frame"
    
    x[, b:=3:4]
    #Warnmeldung:
    #In `[.data.table`(x, , `:=`(b, 3:4)) :
    #  Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
    
    z <- data.frame(a = 1:2)
    class(z) <- c("data.table", "data.frame")
    z[, b:=3:4]
    #Warnmeldung:
    #In `[.data.table`(x, , `:=`(b, 3:4)) :
    #  Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
    

提交回复
热议问题