change object name in loop inR - r

I have a for loop which reads in a different RData file in each iteration and that works well with just paste.
However, once the RData file is loaded there is an object loaded called
topy in the first instance of the loop, in the second it is ropy, then eopy and so on.
What I now tried is
vals<-c("topy","ropy","eopy")
paste("vals[i]")->r
to assign these different objects to r which is used further in the script and is overwirtten in every step of the loop. But that does not work. Topy and ropy and the rest ar matrixes.
When I load the RData file and then just type manually topy the matrix will be shown but if I do paste and then type r it will only show "topy". I also tried assign - did not work..any idea?

I'm not sure whether I got your point, is the following what you need?
p <-parse(text=vals[i])
r <- eval(p)

Related

Looping through nc files in R

Good morning everyone,
I am currently using the code written by Antonio Olinto Avila-da-Silva on this link: https://oceancolor.gsfc.nasa.gov/forum/oceancolor/topic_show.pl?tid=5954
It allows me to extract data of type sst/chlor_a from nc file. It uses a loop to create an excel file with all the data. Unfortunately, I noticed that the function only takes the first data file in the loop. Thus, I find myself with 20 times the same data in a row in my excel file.
Does anyone have a solution to make this loop work properly?
I would first check out that these two lines contain all the files you are expecting:
(f <- list.files(".", pattern="*.L3m_MO_SST_sst_9km.nc",full.names=F))
(lf<-length(f))
And then there's a bug in the for-loop. This line:
data<-nc_open(f)
Needs to reference the iterator i, so change it to something like this:
data<-nc_open(f[[i]])
It appears both scripts have this same bug.

Loading and removing datasets using paste in R

I have a large number of similarly named .R datasets. I am trying to load them in (which i can do successfully), do something to them and then remove them from the workspace all in one loop. I am struggling however to remove them because they are in the wrong class coming out of the paste command. While I know whats wrong, I have no idea how to correct my code, so suggestions are welcome. Here is some example code
for(i in 1:n){
load(paste("C",i,".R",sep=""))
# do stuff to dataset
rm(paste("C",i,sep="")) #this line is clearly wrong
}
Thanks for the help
The list argument of rm should do what you want. It takes character of variable names which are removed. So, something like this should work:
for (i in 1:n) {
loaded <- load(paste0("C", i, ".R"))
# do stuff to dataset
rm(list = loaded)
}
Note, that the load function returns a character with the names of the loaded object(s). So we can use that when removing the loaded object(s) again. The loaded object(s) with load does not nessesarily correspond to the filename.

How to import multiple matlab files into R (Using package R.Matlab)

Thank you in advance for your're help. I am using R to analyse some data that is initially created in Matlab. I am using the package "R.Matlab" and it is fantastic for 1 file, but I am struggling to import multiple files.
The working script for a single file is as follows...
install.packages("R.matlab")
library(R.matlab)
x<-("folder_of_files")
path <- system.file("/home/ashley/Desktop/Save/2D Stream", package="R.matlab")
pathname <- file.path(x, "Test0000.mat")
data1 <- readMat(pathname)
And this works fantastic. The format of my files is 'Name_0000.mat' where between files the name is a constant and the 4 digits increase, but not necesserally by 1.
My attempt to load multiple files at once was along these lines...
for (i in 1:length(temp))
data1<-list()
{data1[[i]] <- readMat((get(paste(temp[i]))))}
And also in multiple other ways that included and excluded path and pathname from the loop, all of which give me the same error:
Error in get(paste(temp[i])) :
object 'Test0825.mat' not found
Where 0825 is my final file name. If you change the length of the loop it is always just the name of the final one.
I think the issue is that when it pastes the name it looks for that object, which as of yet does not exist so I need to have the pasted text in speach marks, yet I dont know how to do that.
Sorry this was such a long post....Many thanks

Best practice for naming archived objects?

I've got a function that has a list output. Every time I run it, I want to export the results with save. After a couple of runs I want to read the files in and compare the results. I do this, because I don't know how many tasks there will be, and maybe I'll use different computers to calculate each task. So how should I name the archived objects, so later I can read them all in?
My best guess would be to dynamically name the variables before saving, and keep track of the object names, but I've read everywhere that this is a big no-no.
So how should I approach this problem?
You might want to use the saveRDS and readRDS functions instead of save and load. The RDS version functions will save and read single objects without the attached name. You would create your object and save it to a file (using paste0 or sprintf to create unique names), then when processing the results you can read in one object at a time, or read several into a list to work with them.
You can use scope to hide the retrieved name inside a function, so first you might save a list to a file:
mybiglist <- list(fred=1, john='dum di dum', mary=3)
save(mybiglist, file='mybiglist1.RData')
Then you can load it back in through a function and give it whatever name you like be it inside another list or just a plain object:
# Use the fact that load returns the name of the object loaded
# and that scope will hide this object
myspecialload <- function(RD.fnam) {
return(eval(parse(text=load(RD.fnam))))
}
# now lets reload that file but put it in another object
mynewbiglist <- myspecialload('mybiglist1.RData')
mynewbiglist
$fred
[1] 1
$john
[1] "dum di dum"
$mary
[1] 3
Note that this is not really a generic 'use it anywhere' type function, as for an RData file with multiple objects it appears to return the last object saved... so best stick with one list object per file for now!
One time I was given several RData files, and they all had only one variable called x. In order to read all of them in my workspace, I loaded sequentially each the variable to its environment, and I used get() to read its value.
tenv <- new.env()
load("file_1.RData", envir = tenv)
ls(tenv) # x
myvar1 <- get(ls(tenv), tenv)
rm(tenv)
....
This code can be repeated for each file.

Store a variable directly from loading in r

I have an RData "E.g.RData"
I loaded it into R console using the load function.
load("E.g.RData")
it has a variable e.g. in RData.
I am doing like this -
e <- load("E.g.RData")
then e gets the character vector as "e.g."
but I want the contents of e.g. into e.
Is there a way to do it in R?
Yeah, the problem is that E.g maintains its name during the saving of the object. You could try assigning the new name "e" to the E.g. object and then remove the E.g. object:
E.g <- runif(100)
save(E.g, file="E.g.Rdata")
load("E.g.Rdata")
assign("e", E.g)
rm(E.g)
This can be done using:
y <- get(load("path/E.g.RData"))
y will contain the contents of the e.g. variable.
Rather than using the load function with its defaults, which overwrites anything of the same name in the global workspace, you may prefer to use attach to attach the workspace, then copy just the object(s) of interest with the names you want, then detach the workspace.

Resources