Not executing source - r

source() function executes R commands which is written inside the script. Is there any way to load the script from different file location but not execute it. Alternative to source("getdata.R") for just loading the file.

It's litte awkward to do it and I am not sure if this is the way you wanted it but in any case, here is one way to do it. Use readLines to read the entire script. then save it as an obj with paste0 like below. You may want to execute it later. So for that you can use NSE functions like eval and parse to execute it.
dt <- readLines('E:\\script.R')
obj <- paste0(dt, collapse = '\n')
eval(parse(text = obj), envir=.GlobalEnv)
# contents of script.R
#script.R
x <- 20
y <- 30
print(x + y)
print('objects are printed')
An alternate way could be this also, wrapping the source call inside a function, whenever you want to execute it then call the function instead.
func_source <- function(file='E:\\script.R'){
source(file)
}
## call the function
func_source()

Related

How to read results from one R script to another

Is there anyway I can store the results of one variable in one R script, and make them available to another R script?
I have this basic script in one file:
B5b=fit(y~.,d_treino_both,model="randomforest",task="class")
P5b=predict(B5b,d_teste)
x=d_teste$y
m5b=mmetric(x,P5b,metric=c("ACC","ACCLASS","CONF", "ROC"))
mgraph(x,P5b,graph= "ROC", baseline=TRUE)
print(m5b)
P5b
Then, I want to make the resuts of P5b variable available to another script.
Any help?
Not sure if this is what you are looking for. I think one way you can do that is to source the script1 in script2. I would do something like this and remove any additional variables using rm.
source("script1.R")
Perhaps you could try something with dput and the clipboard. Basically, this is just copying the dput of an object to the clipboard and then evaluating the clipboard in the second script. Note that you cannot use the clipboard in the meantime.
# first script
obj <- capture.output(dput(matrix(1:100, 10, 10)))
writeClipboard(str = obj)
# second script
obj2 <- eval(parse(text = readClipboard()))

how to make R script stop when it has to read a line?

I want this code to ask for the value of x while I run the whole script but it doesn't wait for the input. Although it waits for a file to get uploaded by the user at line 3. While running it line by line this works fine and that is obvious. What is the best method to this?
x = readline("how many columns?")
Data = read.csv(file.choose())
columns = matrix(rep(0, dim(Data[1] * x), nrow = dim(Data)[1]))
Data = cbind(Data, columns)
because when you run whole the script, it can't wait to get the x value.
You can put the script into a function, then call the function.
It will run line by line.
your_func_name <- function()
{
#your script
}
Whenever you wanna call the script:
#just call the function
your_func_name()

Trying to save everything in R environment to disk

I need to save items in my environment in R to disk. I can't figure out why the following code doesn't work :
op <- function(){
for(i in 1:length(ls())){
file <- paste0(ls()[i],".Rds")
saveRDS(file,file)
}
}
There are actually couple things wrong here:
I suspect you want to save .GlobalEnv, not just op's environment. However the calls to ls will list objects in op's environment (which is only i by the time you call ls). If you want to list object in .GlobalEnv, call ls(.GlobalEnv)
Also, when you are calling saveRDS, you are telling it to save a string stored in file into path stored in file. So you are essentially only saving the path. Instead you need to get the object from .GlobalEnv
So one of correct ways to do it would be:
op <- function(){
obj_names <- ls(.GlobalEnv)
for(i in 1:length(obj_names){
file <- paste0(obj_names[i],".Rds")
saveRDS(get(obj_names[i], envir = .GlobalEnv), file)
}
}
Or a bit more idiomatic,
op <- function()
sapply(ls(.GlobalEnv), function(x) saveRDS(get(x, envir = .GlobalEnv), paste0(x, ".Rds"))
Also save function might be useful, if you don't mind saving all objects in one file. More at ?save
The code you wrote only saves a list of files with names identical to the names in the environment of your function (i.e. a single file "i.rds").
If you want to save the contents of an environment to a file, you might want to try the save() or save.image() function which does exactly what you are looking for.
For information try ?save. Here is some code:
a <- 1
b <- 2
save(list=ls(), file="myfile.rda")
rm(list=ls())
load(file="myfile.rda")
ls()
yielding:
[1] "a" "b"

How to import only functions from .R file without executing the whole file

Let's say I have a R script, testScript.R
test <- function(){cat('Hello world')}
cat('Bye world')
In the R-console, I understand I can import the function, test() by
source('testScript.R')
However at the same time, it will also execute cat('Bye world'). Assuming it is not allowed to create/modify files, is there a way to import only the function, test() without executing cat('Bye world')?
First of all, let me say that this really isn't a good idea. R is a functional programming language so functions are just like regular objects. There's not a strong separation between calling a function and assigning a function. These are all pretty much the same thing
a <- function(a) a+1
a(6)
# [1] 7
assign("a", function(i) i+1)
a(6)
# [1] 7
`<-`(a, function(i) i+1)
a(6)
# [1] 7
There's no difference between defining a function and calling an assignment function. You never know what the code inside a function will do unless you run it; therefore it's not easy to tell which code creates "functions" and which does not. As #mdsumner pointed out, you would be better off manual separating the code you used to define functions and the code you use to run them.
That said, if you wanted to extract all the variable assignments where you use <- from a code file, you could do
cmds <- parse("fakeload.R")
assign.funs <- sapply(cmds, function(x) {
if(x[[1]]=="<-") {
if(x[[3]][[1]]=="function") {
return(TRUE)
}
}
return(FALSE)
})
eval(cmds[assign.funs])
This will evaluate all the function assignments of the "standard" form.
Oh man... that's interesting. I don't know of any way to do that without some atrocity like this:
# assume your two like script is stored in testScript.R
a <- readLines("testScript.R")
a <- paste(a, collapse="\n")
library(stringr)
func_string <- str_extract(a, "[a-z]+ <- function.+}")
test <- eval(parse(text=func_string))
> test()
Hello world
You will certainly need to work on the regex to extract your functions. And str_extract_all() will be helpful if there's more than one function. Good luck.

R: Name an object created within a function with a name defined by the function

I need to simulate some data, and I would like to have a function with everything built in, so I just need to run
simulate(scenario="xxx")
This function stores all the simulated datasets for the designated scenario in a list called simdat. Within the function, I want to rename that list "simdat.xxx" and save it out as "simdat_xxx.RData", so later on I can just load this file and have access to the list simdat.xxx. I need the list to have a name that refers specifically to which batch it is, because I am dealing with a lot of batches and I may want to load several at the same time.
Is there a way to, within a function, make a name and use it to name an object? I searched over and over again and could not find a way to do this. In desperation, I am resorting to doing this: within the function,
(a) write a temporary script using paste, which looks like this
temp.fn <- function(simdat){
simdat.xxx <- simdat
save(simdat.xxx,file="simdat_xxx.RData")
}
(b) use writeLines to write it out to a .R file
(c) source the file
(d) run it
This seriously seems like overkill to me. Is there a better way to do this?
Thanks much for your help!
Trang
Try this,
simulate <- function(scenario="xxx"){
simdat <- replicate(4, rnorm(10), simplify=FALSE)
data_name <- paste("simdat", scenario, sep=".")
assign(data_name, simdat)
save(list = data_name, file = paste0("simdat_", scenario, ".Rdata"))
}

Resources