Data.table包在我不期望它的情况下在全局环境中将data.frame
设置为data.table
。我该如何预防?
示例1:Data.frame
作为参数传递给函数。那么data.frame
在全球环境中就是data.table
。
df1 <- data.frame(v1 = 1:5, v2 = 6:10)
# some function which uses data.table
foo <- function(df){
setDT(df)
df[,v3 := v1 + v2]
return("hello")
}
foo(df1)
[1] "hello"
str(df1)
Classes ‘data.table’ and 'data.frame': 5 obs. of 2 variables:
$ v1: int 1 2 3 4 5
$ v2: int 6 7 8 9 10
示例2:Data.frame
作为参数传递给函数。在函数内部,data.frame
被复制到其他变量中,此副本被视为data.table
。原始data.frame
在全球环境中再次为data.table
。
df2 <- data.frame(v1 = 1:5, v2 = 6:10)
# some function which uses data.table
bar <- function(df){
df_temp <- df # store value in different variable
setDT(df_temp)
df_temp[,v3 := v1 + v2]
return("hello")
}
bar(df2)
[1] "hello"
str(df2)
Classes ‘data.table’ and 'data.frame': 5 obs. of 2 variables:
$ v1: int 1 2 3 4 5
$ v2: int 6 7 8 9 10