Just a question... supposing I have the following R file, called script.R:
calculation1 <- function(){
# multiple calculations goes here.
}
calculation2 <- function(){
# multiple calculations goes here.
}
And I want to open this file on another file in order to use calculation1 and calculation2 multiple times in different cases.
Is that possible? I mean, something like the following.
calculation_script <- Some way, function or method that instantiate script.R in this variable.
calculation_script.calculation1()
calculation_script.calculation2()
I need to do this because I need to open script.R file in a Tableau Calculated field.
Related
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()))
I have written a R script for binning on the specific parameters of several .csv files in the same folder. I used the smbinning package. When I execute the script, it produces detailed results. I do not need all of them. I want to take a specific part of the results and write into a .csv file automatically. Can someone tell me how can I do this? My R script, details results, and wanted parts of result is as follows
My R script is as follows:
library(smbinning)
files <- list.files(pattern = "0.csv")
cutpoint <- rep(0,length(files))
for(i in 1:length(files)){
data <- read.csv(files[i],header=T)
df.train <- data.frame(data)
df.train_amp <-rbind(df.train)
cutpoint[i] <- smbinning(df=df.train_amp, y="cvflg",x="dwell")
}
result <- cbind(files,cutpoint)
write.csv(result,"result_dwell.csv")
You can use View(result) to see if the variable contains exactly what your require. Else there is something wrong in your logic.
There is function sink in R which writes the output of a program to a file.
https://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html
I would like to access, update and run an R script from another R script. Specifically, I would like to create a loop that reads in the lines of another R script in order to update some variable names by adding increments of 1 to each of them. Once the variables have been updated, I would like to run the R script.
Currently my code for this is as follows:
for (i in 1:n) {
x <- readLines("Mscript0.R")
y <- gsub(paste0("Mtrain",i),paste0("Mtrain",i+1), x)
cat(y, file="Mscript0.R", sep="\n")
source("Mscript0.R")
}
Please note that the string "Mtrain" in the source script takes on various different forms such as:
Mtrain4 <- read.csv("Mtrain4.csv",header=T,sep=",")
s <- Mtrain4$Weight
Any Ideas?
Thanks
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"))
}
this is an atomic example of my current issue:
For the moment I have a project containing several R scripts (all in the same directory named DIR). I have a main script in DIR sourcing all the R files and, containing a basicconfig:
basicConfig()
I take two scripts in DIR, dog.r and cat.r. I have currently only one function in these scripts. In dog.r :
feedDog <- function(){
loginfo("The dog is happy to eat!", logger="dog.r")
}
And in cat.r :
feedCat <- function(){
loginfo("The cat is voracious", logger="cat.r")
}
It's fine with this example. But in real I have something like 20 scripts and 20 possible error messages in each. So that instead of writting:
loginfo("some message", logger="name of script")
I would like to write:
loginfo("some message", logger=logger)
And configure different loggers.
The issue is that if I declare a logger in each R scripts, only one will be taken into account when I source all files with my main ... I dunno how to bypass this issue.
PS: in Python it is possible to define a logger in each file taking automatically the name of the script like this:
logger = logging.getLogger(__name__)
But I am afraid it is not possible in R ?
If your source() a file, the functions created in that file will have an attribute called srcref that stored the location from the sourced file that the function came from. If you have a name that points to that function, you can use getSrcFilename to get the filename the function came from. For example, create a file that we can source
# -- testthis.R --
testthis <- function() {
loginfo("Hello")
}
Now if we enter R, we can run
loginfo <-function(msg) {
fnname <- sys.call(-1)[[1]]
fnfile <- getSrcFilename(eval(fnname))
paste(msg, "from", deparse(fnname), "in", fnfile)
}
source("testthis.R")
testthis()
# [1] "Hello from testthis in testthis.R"
The function loginfo uses sys.call(-1) to see what function it was called from. Then it extracts the name from that call (with [[1]]) and then we use eval() to turn that "name" object into the actual function. Once we have the function, we can get the source file name. This is the same as running
getSrcFilename(testthis)
if you already knew the name of the function. So it is possible, it's just a bit tricky. I believe this special attribute is only added to functions. Other than that, each source file doesn't get it's own namespace or anything so they can't each have their own logger.