How to rename the database (Rdata) in R?

Asked

Viewed 726 times

5

I have the following situation: I need to merge two banks. The name of both the database files are: banco2.RData and banco2_2.rdata

However, when I open the banks in the R they have the same name: banco2, actually do not open in the same environment, because of the duplicity of names. Because of this I can not merge.

So how can I change the name banco2 for the database that is opened in R?

2 answers

5


Upload the file banco2_2.rdata in the R. Use the command

banco2_2 <- banco2

to create the data frame banco2_2. Upload the file banco2.RData in the R. The banco2 old will be replaced. Merge between banco2_2 and banco2.

  • Marcus Nunes, thank you for your help. It worked!

3

Really this is a data problem in format .rdata, because you don’t know what’s inside the file and they can overwrite various things. If you do this manually it can be quite complicated, you will have to read a file, rename all objects, then read the other file and so on.

One solution is not to upload your files to your main desktop. You create a separate environment and upload the files there. Let me give you an example.

Let’s create two files .rda example containing objects with the same name:

rm(list = ls())
save(mtcars, iris, file = "dados1.rda")
save(mtcars, iris, file = "dados2.rda")

Now suppose you want to read these files but don’t want the objects to be overwritten.

The first thing you have to do is create a new environment (it’s like a list):

dados1 <- new.env()

And now it’s time to give load() you will speak to give load() in that environment.

load("dados1.rda", envir = dados1)

If you want to access the data you access as if it were a list:

dados1$iris
dados1$mtcars

Now you can read the dados2.rda without overwriting the objects of dados1:

dados2 <- new.env()
load("dados2.rda", envir = dados2)

If you don’t want to work with environments you can turn them into list:

dados1 <- as.list(dados1)

But if you are going through too much of this problem, it might be a good idea to save the files in format .rds so you can read with whatever name you want, without having to do all this gymnastics.

  • Thank you very much, Carlos!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.