How to rename the database (RData) in R?

5

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

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

So, how can I change the name banco2 for the database that opens in R?

    
asked by anonymous 06.03.2017 / 18:59

2 answers

3

Load the file banco2_2.rdata into R . Use the

banco2_2 <- banco2

to create the data frame banco2_2 . Load banco2.RData into R . The% old% will be overwritten. Make the merge between banco2 and banco2_2 .

    
06.03.2017 / 19:28
2

This is really a problem with the data in .rdata format, because you do not know what's inside the file and they can overwrite several things. If you do this manually it can be quite tricky, you'll have to read a file, rename all the objects, then read the other file, and so on.

One solution is to not upload your files to your primary workspace. You create a separate environment and load the files there. I'll give you an example.

Let's create two sample .rda files that contain 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 do not 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're going to talk 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 dados2.rda without overwriting dados1 objects:

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

If you do not want to work with environments you can turn them into a list:

dados1 <- as.list(dados1)

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

    
06.03.2017 / 19:43