RStudio: copy single dataframe from one project folder to another?

Viewed 598

Is there a simple one line function to copy a single dataframe from one project folder to another? (Windows) I.e., not exporting the df out to txt or csv and then importing in.

2 Answers

I assume you mean you want to save the data into the workspace file that is held in .RData within the project folder.

This is actually just an external representation of the objects that were in your workspace when you closed the project last. They are simply written out to disk to the .RData file.

Imagine you had Project1 which contained one data frame named df1.

df1 <- mtcars

When you close Project1, df1 will be written to .RData.

Now imagine you are working in Project2 where you have a second data frame, df2:

df2 <- iris

You could load the Project1 .RData file into a new environment using load():

Project1 <- new.env()
load("~/Project1/.RData",env = Project1)

Now you can assign df2 into that environment:

assign("df2", df2, envir = Project1)
ls(envir = Project1)
[1] "df1" "df2"

Finally, you can write the contents of that environment back into the first project's directory:

save(list = ls(all.names = TRUE, envir = Project1),
     file = "~/Project1/.RData", envir = Project1)

When you open Project1 again, df2 should be loaded:

ls()
[1] "df1" "df2"

If the file is not already loaded into memory in R, one can use file.copy() to copy a file from one directory to another. We'll copy one of the Pokemon CSV files from the PokemonData project directory to the datascience project's data subdirectory.

getwd()
# show the files in "from" directory
list.files(path="../PokemonData/",pattern="*.csv")
# show the files in "to" directory matching pattern of gen0?.csv
list.files(path="./data/",pattern="^gen0*")

file.copy("../PokemonData/gen01.csv",
          "./data/gen01.csv")

# show the files in "to" directory matching pattern of gen0?.csv
list.files(path="./data/",pattern="^gen0*")

...and the output:

> getwd()
[1] "/Users/lgreski/gitrepos/datascience"
> # show the files in "from" directory
> list.files(path="../PokemonData/",pattern="*.csv")
[1] "gen01.csv"   "gen02.csv"   "gen03.csv"   "gen04.csv"   "gen05.csv"   "gen06.csv"  
[7] "gen07.csv"   "gen08.csv"   "Pokemon.csv"
> # show the files in "to" directory matching pattern of gen0?.csv
> list.files(path="./data/",pattern="^gen0*")
character(0)
> 
> file.copy("../PokemonData/gen01.csv",
+           "./data/gen01.csv")
[1] TRUE
> 
> # show the files in "to" directory matching pattern of gen0?.csv
> list.files(path="./data/",pattern="^gen0*")
[1] "gen01.csv"

The same procedure works with an R save file.

Related