让我们假设有df
:
df <- data.frame(A = 1 : 3, B = 2 : 4, C = 3 : 5, D = 4 : 6)
现在我想从df
中删除列A
,我被教导的方式是使用subset
ting:
df <- df[, c("B", "C", "D")]
# or
df <- subset(df, select = -A)
但是,我今天了解到以下代码也可以工作:
df$A = NULL
这让我问这个问题:
将NULL
分配给数据框列而不是子集化是否是一个好主意?
除了subset
返回一个新对象之外,这两者之间的隐含区别(例如语义、性能)是什么?
我试图用tracemem
、address
和mem_change
来探索它。
不同的方法:
#subset
my_df <- subset(my_df, select = -A)
# <- NULL
my_df$A <- NULL
# set from data.table
set(my_df, j = "A", value = NULL)
# subset with []
my_df <- my_df[, colnames(my_df)[-1]]
结果:
method_name
<memory address from tracemem >
<address of df>
(Possibly tracemem results if object is copied)
memory change when column is deleted
<address of df after column deleted>
subset
[1] "<0x7f92c1504610>"
[1] "0x7f92c1504610"
-178 kB
[1] "0x7f92c1503a10"
子集具有不同的最终地址(在替换 DF 时预期)
<- NULL
[1] "<0x7f92c17b80e0>"
[1] "0x7f92c17b80e0"
tracemem[0x7f92c17b80e0 -> 0x7f92c1719a90]: eval eval mem_change
tracemem[0x7f92c1719a90 -> 0x7f92c1746400]: $<-.data.frame $<- eval eval mem_change
tracemem[0x7f92c1746400 -> 0x7f92c17006c0]: $<-.data.frame $<- eval eval mem_change
-290 kB
[1] "0x7f92c17312e0"
<- NULL
制作一份副本(tracemem 结果;多个副本?),最终地址不同
set from data.table
[1] "<0x7f92c16227c0>"
[1] "0x7f92c16227c0"
-303 kB
[1] "0x7f92c16227c0"
Set 具有相同的最终地址。即使 df 不是 data.table,data.table::set
也会通过引用来修改 data.frame(和 data.tables)。
subset with []
[1] "<0x7f92c165cfa0>"
[1] "0x7f92c165cfa0"
-300 kB
[1] "0x7f92c161e950"
带有 [] 的子集也具有不同的最终地址
完整代码:
.create_data <- function() {
suppressWarnings(my_df <-
data.frame(matrix(rnorm(1000000),
ncol = length(LETTERS))))
colnames(my_df) <- copy(LETTERS)
my_df
}
library(pryr)
library(data.table)
##### subset
message("subset")
my_df <- .create_data()
tracemem(my_df)
address(my_df)
mem_change(my_df <- subset(my_df, select = -A))
address(my_df)
untracemem(my_df)
rm(my_df)
invisible(gc())
##### <- NULL
message("<- NULL")
my_df <- .create_data()
tracemem(my_df)
address(my_df)
mem_change(my_df$A <- NULL)
address(my_df)
untracemem(my_df)
rm(my_df)
invisible(gc())
##### set from data.table
message("set from data.table")
my_df <- .create_data()
tracemem(my_df)
address(my_df)
mem_change(set(my_df, j = "A", value = NULL))
address(my_df)
untracemem(my_df)
rm(my_df)
invisible(gc())
##### subset with []
message("subset with []")
my_df <- .create_data()
tracemem(my_df)
address(my_df)
mem_change(my_df <- my_df[, colnames(my_df)[-1]])
address(my_df)
untracemem(my_df)
rm(my_df)
invisible(gc())