Q:

How do I create a copy of a data frame in R

I want to duplicate the full contents of a data frame that has been read in from a *.csv file. I don't believe it is a duplication if I do copyOfFirstFrame <- firstFrame. So what do I need to do?
firstFrame <- read_csv("fileName.csv")
copyOfFirstFrame <- ?????

If I do the following the memory address remains the same.
copyOfFirstFrame <- firstFrame
tracemem(firstFrame) == tracemem(copyOfFirstFrame)
[1] TRUE

The copy must result in two unique memory addresses.  Check In R, how can I check if two variable names reference the same underlying object? for details.

A:

Let DATA be a pre-existing data frame object.
I am creating a new object, COPY which is an exact copy of DATA, but it occupies a different memory location and hence doesn't point to the original data frame.
I use the function data.frame() like this:
> COPY<-data.frame(DATA)

I check whether the memory addresses are same or not using tracemem():
> tracemem(COPY)==tracemem(DATA)
> [1] FALSE

Lame enough, I think.

A:

Using cbind with one data.frame will ensure you have a copy:
> df <- cbind(NA, NA)
> df2 <- cbind(df)
> df2
     [,1] [,2]
[1,]   NA   NA
> df2[,1] <- 1
> df
     [,1] [,2]
[1,]   NA   NA
> df2
     [,1] [,2]
[1,]    1   NA
> 

A:

Alternatively we can use data.table::copy().
df.1 <- data.frame(1)

library(data.table)
df.2 <- copy(df.1)

> tracemem(df.1) == tracemem(df.2)
[1] FALSE

