0

The context: I was trying to swap values in two data.table columns and have since found the answer here:

Swapping values between two columns using data.table

While attempting the swap by joining data.tables and assigning values from one table to the other, I discovered some strange behaviour from data.table. Here is a reproducible example:

## create data table and bind one row
a <- data.table(idcol = integer(), col1 = character(), col2 = character())
a <- rbindlist(list(a, list(1, 'left value', 'right value')))
## view a to see that the left value is in col1 as expected
a
## make two copies of a
b <- a
c <- a
## join b and c and assign col1 and col2 to i.col2 and i.col1 respectively to 
## effectively swap the values in b
b[c, on='idcol', `:=`(col1 = i.col2, col2 = i.col1)]
## looking at each data.table below, somehow a was updated??? I feel like I'm 
going crazy.
a
b

As you can see my comment, somehow the original table "a" is updated with the swapped values as well as in the two copies (tables "b" and "c") even though I did not use "a" in the join/assignment. Like I said, I found the answer to my original question of how to swap but I thought this was strange enough to post.

How is this possible? Am I going crazy? Thanks!

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
moki
  • 110
  • 3
  • 13

0 Answers0