Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

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.

like image 821
user1605665 Avatar asked Jan 24 '16 23:01

user1605665


People also ask

How do I replicate a Dataframe in R?

A replication factor is declared to define the number of times the data frame rows are to be repeated. The do. call() method in R is used to perform an R function while taking as input various arguments. The rbind() method is taken as the first argument of this method to combine data frames together.

How do I copy and paste a Dataframe in R?

You can use the scan function to copy a column of numbers from Excel to R. Copy the column from Excel, run x <- scan() , type Ctrl-v to paste into R, and press enter to signal the end of input to scan .

How do I create a Dataframe from a dataset in R?

How to Create a Data Frame. We can create a dataframe in R by passing the variable a,b,c,d into the data. frame() function. We can R create dataframe and name the columns with name() and simply specify the name of the variables.


2 Answers

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.

like image 106
Dex Avatar answered Oct 09 '22 08:10

Dex


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
> 
like image 12
hd1 Avatar answered Oct 09 '22 09:10

hd1