0

I have a data table

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

I want to keep only columns a,b, and e:

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

my df2 is as expected:

    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

And df1 should've remained the same. But my df1 is as below:

    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

How do I stop df1 from changing when I have already created a df2? I have tried to fix it by doing the following:

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

But I get the same result.

Please help!

pogibas
  • 27,303
  • 19
  • 84
  • 117

3 Answers3

0

Loot at this and try df2 <- copy(df1). df1 will stop changing when playing with df2.

nghauran
  • 6,648
  • 2
  • 20
  • 29
0

try copy in data.table

df2 <- copy(df1)
drop <- c("c", "d")
df2[, (drop):=NULL ]
myincas
  • 1,500
  • 10
  • 15
0

Can you try instead :

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

For me df1 stays the same and df2 becomes what you want. (But I can't tell you why df1 was changing before sorry.)

Aurélien.AB
  • 85
  • 10