I have a dataframe df that is quite large. At some point, I want to save it to the database, using sqlSave(). Since the database table has a mostly similar structure but not quite the same column names, I have some massaging to do first. Therefore, I do the following:
# I believe i'm copying by val
mycopy <- df
# but i also know setnames uses references... so is this the culprit?
setnames(mycopy, names(mycopy)[1], "NewColumnName")
I was horrified to discover due to warnings from other parts of my app) that the original 'df' dataframe, in my Global Environment window in RStudio, had the column names etc renamed!! How do I stop this from happening? Why isn't setnames() pointing at 'mycopy' instead of the original 'df'?
UPDATE: reproducible example:
library(data.table) # for setnames
df <- data.frame(foo=c(1,2,3), bar=c(4,5,6))
mycopy <- df
setnames(mycopy, names(mycopy)[1], "NewColumnName")
str(df)
yields this:
> str(df)
'data.frame': 3 obs. of 2 variables:
$ NewColumnName: num 1 2 3
$ bar : num 4 5 6
this should not happen?