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

查看:13
本文介绍了是否可以就地(破坏性地)修改 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?

Is it possible to do that with a vanilla 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天全站免登陆