How do I empty a list in R? - r

I have a file with an R program. I load it interactively on R and then I call the main function. During the execution I fill up some global lists but when I run the main function again I want those lists to be empty. How can I empty a filled up list? I tried doing
list <- NULL
after execution but it didn't work.

Since you are setting them globally, you probably need list <<- NULL, because the <<- operator assigns global variables.
Edit, per #Dason's comment:
The <<- operator can in some circumstances fail to change the value of a variable in all possible environments. For that reason, it is better to use
assign("list", NULL, envir = .GlobalEnv)

Related

R thinks argument is a function but actually is a variable

In the RShiny package (for web applications) you have reactive variables (update automatically when something in the UI changes). When you use these variables you need to use this syntax: variable() with brackets at the end of the variable name.
I need this reactive variable as input for one of my functions. I call this function in the server.R part. There I use function(infile = fa_archive(), ...) but R thinks that fa_archive() is a function instead of a variable. Probably because of the parentheses, but it isn't. I am 100% sure the variable fa_archive is defined. Beforehand I only needed fa_archive[[1]]() as input and then my function worked fine. But now I needed to "upgrade" my function as to include more files at once and when I use fa_archive() as input variable in the function it recognizes it as a function and returns
Error: Could not find function "fa_archive()"
I have not really tried solving this, because it just seems so weird that using the full variable instead of a part of it ([[1]]) should change this so drastically. Here is the relevant piece of my code
fa_archive <- list(
reactive({ fa_archive_function(input$model1, as.integer(input$lag1)) }),
reactive({ fa_archive_function(input$model2, as.integer(input$lag2)) }),
reactive({ fa_archive_function(input$model3, as.integer(input$lag3)) }),
reactive({ fa_archive_function(input$model4, as.integer(input$lag4)) }))
output$plotSounding1Da <- renderPlot({ plot_profile(infile= fa_archive() , fcdate=fcdate(), ldt=ldt(), prm=input$prmSounding, location=input$location, recent=recent(), add=FALSE)}, width=400, height=500)
When you use [reactive] variables you need to use this syntax: variable() with brackets at the end of the variable name.
Correct. But this only works on a reactive variable. And your fa_archive() isn’t a reactive variable, it’s a normal R lits. That’s why R complains.
Just surrounding the list call with reactive(…) probably won’t work though, because your code has other issues that need fixing. Without knowing what exactly plot_profile does, it’s unlikely that it expects a list of reactive components as an argument.

lapply and the save function in R

I have created a list of objects in my work environment
data <- c("variable1", "variable2", "variable3")
i would like to save the files to different directories with the variable name as the directory... so i did this to give me a list of file names to pass to the save function via lapply..
paste0(data,"/",data,".rda")
lapply(data,FUN=save,file = paste0(data,"/",data,".rda"))
i get the error
Error in FUN(X[[i]], ...) : object ‘X[[i]]’ not found
i'm not sure what i'm doing wrong here..
Do you have a list of objects, or a list of names of objects? You say you have the former, but the code you give is for the latter.
Also, if you only have one object per file, then it's better to use the saveRDS function (and loadRDS to load it).
lapply(data, function(x) saveRDS(get(x), paste0(x, "/", x, ".rds")))
If you have to use save:
lapply(data, function(x) save(list=x, file=paste0(x, "/", x, ".rds")))
Several things going on here.
First, you need not use lapply when you don't care about the return value of the function called at each iteration. It offers nothing in this case.
Second, and more importantly, what you are doing is writing objects to files with names derived from their variable names in R. That's an anti-pattern.
Instead, create a list of the objects, and use for for the work. We need to use saveRDS for this (thanks Hong Ooi) as l[[n]] is also not the name of an object in the environment.
l <- list(variable1 = variable1, variable2 = variable2, variable3=variable3)
for (n in names(l)) {
fname = paste0(n, '/', n, '.rda')
saveRDS(file=fname, l[[n]])
}
It would be better to just save the entire list, but then all the data would be in one file in one directory.
As for what's actually wrong with your code:
You pass the same value for file to all invocations of save, and you don't intend to do so. This value is a vector, but what you want is that each iteration gets one element from this vector.
The way lapply computes the value to pass to the function confuses save. In particular, it does this:
names <- as.character(substitute(list(...)))[-1L]
That results in something like the following, which is not the name of an object in the environment.
c("variable1", "variable2", "variable3")[[1]]

Using delayed assignment in a function: How do I send the promise back to the parent environment?

I would like to used delayedAssign to load a series of data from a set of files only when the data is needed. But since these files will always be in the same directory (which may be moved around), instead of hard coding the location of each file (which would be tedious to change later on if the directory was moved), I would like to simply make a function that accepts the filepath for the directory.
loadLayers <- function(filepath) {
delayedAssign("dataset1", readRDS(file.path(filepath, "experiment1.rds")))
delayedAssign("dataset2", readRDS(file.path(filepath, "experiment2.rds")))
delayedAssign("dataset3", readRDS(file.path(filepath,"experiment3.rds")))
return (list <- (setOne = dataset1, setTwo = dataset2, setThree = dataset3)
}
So instead of loading all the data sets at the start, I'd like to have each data set loaded only when needed (which speeds up the shiny app).
However, I'm having trouble when doing this in a function. It works when the delayedAssign is not in a function, but when I put them in a function, all the objects in the list simply return null, and the "promise" to evaluate them when needed doesn't seem to be fulfilled.
What would be the correct way to achieve this?
Thanks.
Your example code doesn't work in R, but even conceptually, you're using delayedAssign and then you immediately resolve it by referencing it in return() so you end up loading everything anyway. To make it clear, assignments are binding a symbol to a value in an enviroment. So in order for it to make any sense your function must return the environment, not a list. Or, you can simply use the global environment and the function doesn't need to return anything as you use it for its side-effect.
loadLayers <- function(filepath, where=.GlobalEnv) {
delayedAssign("dataset1", readRDS(file.path(filepath, "experiment1.rds")),
assign.env=where)
delayedAssign("dataset2", readRDS(file.path(filepath, "experiment2.rds")),
assign.env=where)
delayedAssign("dataset3", readRDS(file.path(filepath, "experiment3.rds")),
assign.env=where)
where
}

Lacking output strings when using function in R

I'm having a problem with the below function:
ab<-matrix(c(1:20),nrow=4)
rownames(ab)<-c("a","b","c","d")
cd<-c("a","c")
test<-function(x,y,ID_Tag){
for(i in y) {
M_scaled<-t(scale(t(x),center=T))
a<-quantile(M_scaled[match(i,rownames(x)),])
assign(paste0("Probes_",ID_Tag,"_quan_",i),a)
}
}
test(ab,cd,"C1")
x is the dataframe/matrix
y is the string I need to search for in rownames(x)
ID_Tag is is the number I use to distinguish my samples from each other.
The function is running, but no output is generated into strings afterwards.
Hope somebody can help me
When you use assign within a function it will make the assignment to a variable that is accessible within that function only (i.e. it's like using <-). To get around this, you need to specify the envir argument in assign to be either the global environment globalenv() or the parent frame of the function. So try changing your assign statement to
assign(..., envir = parent.frame())
or
assign(..., envir = globalenv())
depending on what you want exactly (in the example you provided they are equivalent). Have a look at ?parent.frame for more info on these. Another possibility is to specify the pos argument in assign, check ?assign.
As an aside, assigning global objects from within a function can lead to various problems in general. I find it better practice in your example to return a list of objects created in the for loop rather than use assign.

retrieving object definition in R studio

I've been defining some variables with the "<-", like
elect<- copPob12$nivelaprob[copPob12$dispelect==5]
I can see their numerical values on the global environment,
but I want to see how I defined them, to be sure about the function I used, because they are subsets within subsets, I can find them in the "History" tab, but that takes too long,
any function that can retrieve the way I defined the variable on the console?
thanks a lot
As I see the problem, may be you are looking for this:
elect <<- copPob12$nivelaprob[copPob12$dispelect==5]
or you can write
elect <- copPob12$nivelaprob[copPob12$dispelect==5]
assign("elect", elect , envir = .GlobalEnv)
here it changes environment as global so it works within function also

Resources