0

I am VERY confused with the following: Using data.table I am creating a dataframe as a copy of an existing one. Then I create a new column in the new dataframe ... and the original dataframe gets the new column also!

df1<- c("A", "B", "C", "D", "E")
df1<-data.table(df1)
> head(df1)
df1
1:   A
2:   B
3:   C
4:   D
5:   E

df2 <- df1[]
df2 <- df2[,col2:=10,]

> head(df1)
    df1 col2
1:   A   10
2:   B   10
3:   C   10
4:   D   10
5:   E   10

Please notice that the second head() refers to the original dataframe, which I do not want any new column. I tried this using dataframes (NOT data.table) and worked fine.

df1<- c("A", "B", "C", "D", "E")
df1<-as.data.frame(df1)
df2<-df1[]
df2$col2<-10

> head(df1)
  df1
1   A
2   B
3   C
4   D
5   E

Plaese advice. Any help wellcomed

COLO
  • 1,024
  • 16
  • 28

1 Answers1

0

We can use copy and the issue will be resolved

 df2 <- copy(df1)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • did mention that already in the comments – Jaap Mar 03 '16 at 13:17
  • @Jaap I didn't see your comments and also if I see the timings, it is just 8 secs before it. I would count it only if it is at least 15 secs or more. My page didn't update – akrun Mar 03 '16 at 13:18
  • Ok. Thanks for the tip .... but WHY the command df2 <- df2[,col2:=10,] does not work in the way it should??? – COLO Mar 03 '16 at 13:19
  • ok, but why didn't mark it as a dupe then? – Jaap Mar 03 '16 at 13:19
  • @EL_COLO You used a `,` after that. it is not needed. – akrun Mar 03 '16 at 13:19
  • @Jaap I didn't search for a dupe. Anyway, you marked it. so no worries. If you are asking me about dupes, why you didn't mark the `cSplit` question you just answered as a dupe? – akrun Mar 03 '16 at 13:20
  • Why? You do on questions I answer (which is ok) – Jaap Mar 03 '16 at 13:20
  • @Jaap You started it. I have plenty of cases where you close the questions that I answer. It works on both ways. You are not immune.. – akrun Mar 03 '16 at 13:21
  • @Jaap Oh, I see, so this is some kind of a revenge dupe... – akrun Mar 03 '16 at 13:22
  • @akrun, same results without the `,` and same results ... – COLO Mar 03 '16 at 13:22
  • @EL_COLO I get `df2[, col2:= 10];df2# df1 col2 1: A 10 2: B 10 3: C 10 4: D 10 5: E 10` – akrun Mar 03 '16 at 13:24
  • @Jaap When I see an answer that is a sure dupe, I close it. I was doing it in an impartial way. For this, it didn't came to my mind that it will be a dupe. – akrun Mar 03 '16 at 13:25
  • 2
    It is certainly not a revenge dupe. I commented and started a search for a dupe immediately because I knew that this has been asked many times before. This is a very very obvious dupe. The argument that it didn't came to mind is not convincing. – Jaap Mar 03 '16 at 13:29
  • @Jaap I didn't think about the dupe. That is a fact. – akrun Mar 03 '16 at 13:37