如何在生成新的data.table时停止更新基础data.table?

时间:2017-11-08 10:12:40

标签: r data.table

我有一个数据表

library(data.table)
df1 = data.table(a = letters, b = LETTERS, c = rnorm(26), d = rnorm(26), e = rnorm(26))

我想只保留a,b和e列:

drop = c("c", "d")
df2 = df1[, (drop):=NULL ]

我的df2符合预期:

    a b            e
 1: a A  1.387204434
 2: b B -0.950967552
 3: c C  0.190996561
 4: d D  0.968200928
 5: e E  0.505969807
 6: f F  0.752403175
 7: g G -1.479986844
 8: h H -0.062693387
 9: i I  0.248138565
10: j J -0.378118424
11: k K  0.753885597
12: l L -0.327404967
13: m M  0.207232384
14: n N -0.831233746
15: o O  0.707431622
16: p P  0.637026703
17: q Q  1.022647436
18: r R -0.821555325
19: s S  0.491352339
20: t T -0.295109037
21: u U  0.075781246
22: v V -0.002940048
23: w W  0.099779072
24: x X -1.286180979
25: y Y -0.267088884
26: z Z -1.039559926

df1应该保持不变。但我的df1如下:

    a b            e
 1: a A  1.387204434
 2: b B -0.950967552
 3: c C  0.190996561
 4: d D  0.968200928
 5: e E  0.505969807
 6: f F  0.752403175
 7: g G -1.479986844
 8: h H -0.062693387
 9: i I  0.248138565
10: j J -0.378118424
11: k K  0.753885597
12: l L -0.327404967
13: m M  0.207232384
14: n N -0.831233746
15: o O  0.707431622
16: p P  0.637026703
17: q Q  1.022647436
18: r R -0.821555325
19: s S  0.491352339
20: t T -0.295109037
21: u U  0.075781246
22: v V -0.002940048
23: w W  0.099779072
24: x X -1.286180979
25: y Y -0.267088884
26: z Z -1.039559926

如何在创建df2时停止更改df1? 我试图通过执行以下操作来修复它:

df2 = df1
df2 = df2[, (drop):=NULL ]

但我得到了同样的结果。

请帮忙!

3 个答案:

答案 0 :(得分:0)

this点击并尝试df2 <- copy(df1)。使用df1时,df2将停止更改。

答案 1 :(得分:0)

copy

中尝试data.table
df2 <- copy(df1)
drop <- c("c", "d")
df2[, (drop):=NULL ]

答案 2 :(得分:0)

你可以尝试一下:

  

df2 = df1 [,!drop,with = FALSE]

对我来说,df1保持不变,df2成为你想要的。 (但是我不能告诉你为什么df1在抱歉之前发生了变化。)