是否可以在原地(破坏性地)修改data.frame? [英] Is it possible to modify a data.frame in-place (destructively)?

查看:158
本文介绍了是否可以在原地(破坏性地)修改data.frame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎可以在 data.table 中就地添加/删除列,即而不复制将所有其他列转移到新表中。

It appears that one can add/delete a column to a data.table in-place, i.e., without copying all the other columns over to a new table.

可以使用一个 data.frame

PS。我知道如何添加/删除列功能,即创建一个新的框架,而不修改原始的。

PS. I know how to add/delete columns "functionally", i.e., creating a new frame without modifying the original one.

推荐答案

可以通过 data.table :: set 的引用从 data.frame 中删除​​或修改现有列。我怀疑你可以添加一个列而不复制。可以向 data.table 中添加列而不复制的原因是 data.table 过度分配记忆。请参见 ?alloc.col 了解详情。

You can delete or modify an existing column from a data.frame by reference with data.table::set. I doubt you can add a column without making a copy. The reason that you can add a column to a data.table without making a copy is that data.table over allocates memory. See ?alloc.col for more.

R> library(data.table)
R> data(mtcars)
R> tracemem(mtcars)
[1] "<0x59fef68>"
R> set(mtcars, j="mpg", value=NULL)        # remove a column
R> set(mtcars, j="cyl", value=rep(42, 32)) # modify a column
R> untracemem(mtcars)
R> str(mtcars)
'data.frame':   32 obs. of  10 variables:
 $ cyl : num  42 42 42 42 42 42 42 42 42 42 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

与正常的data.frame操作比较

Compare that with normal data.frame operations

R> data(mtcars)
R> tracemem(mtcars)
[1] "<0x6b3ec30>"
R> mtcars[, "mpg"] <- NULL
tracemem[0x6b3ec30 -> 0x84de0c8]: 
tracemem[0x84de0c8 -> 0x84de410]: [<-.data.frame [<- 
tracemem[0x84de410 -> 0x84de6b0]: [<-.data.frame [<- 
R> tracemem(mtcars)
[1] "<0x84dca30>"
R> mtcars[, "cyl"] <- rep(42, 32)
tracemem[0x84dca30 -> 0x84dcc28]: 
tracemem[0x84dcc28 -> 0x84dd018]: [<-.data.frame [<- 
tracemem[0x84dd018 -> 0x84dff70]: [<-.data.frame [<- 
R> untracemem(mtcars)
R> data(mtcars)

这篇关于是否可以在原地(破坏性地)修改data.frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆