How to save a function as new R script? - r

Given a function, how to save it to an R script (.R)?
Save works well with data, but apparently can not create .R data.
Copy pasting from the console to a new script file appears to introduce characters that cause errors.

Take a look at the dump function. That writes files that are R code that can be read back in with source or used in some other way.

I have to ask: why are you writing your functions in the console in the first place? Any number of editors support a "source" call, so you can update the function as you edit. Copy/pasting from the console will carry prompt characters along , if nothing else, so it's a bad idea to begin with.

Related

R Markdown script and R

I am calling one R Markdown script from another R script.Below you can see command
rmarkdown::render((file=paste(path1,"/Dashboard.Rmd",sep="")),params=list(args = myarg))
The script is executed without any problem but is not open automatically.
So can anybody help me how to solve this problem and open this script automatically after running of this command ?
First, your syntax probably isn't doing what you intended. Writing
rmarkdown::render((file=paste(path1,"/Dashboard.Rmd",sep="")),params=list(args = myarg))
will create a new variable named file and use it as the first parameter to rmarkdown::render. A more likely way to get what you want is to write it as
outfile <- rmarkdown::render(paste(path1,"/Dashboard.Rmd",sep=""),
params=list(args = myarg))
This removes the assignment from the first argument, and saves the
result (which is the name of the file that was produced).
Now, on to your question: You need to follow that line with
rstudioapi::viewer(outfile)
to view it in RStudio, or
browseURL(outfile)
elsewhere, because rmarkdown::render doesn't automatically call a previewer.

"filename.rdata" file Exploring and Converting to CSV

I'm no R-programmer (because of the problem I started learning it), I'm using Python, In a forcasting task I got a dataset signalList.rdata of a pheomenen called partial discharge.
I tried some commands to load, open and view, Hardly got a glimps
my_data <- get(load('C:/Users/Zack-PC/Desktop/Study/Data Sets/pdCluster/signalList.Rdata'))
but, since i lack deep knowledge about R, I wanted to convert it into a csv file, or any type that I can deal with in python.
or, explore it and copy-paste manually.
so, i'm asking for any solution whether using R or Python or any tool to get what's in the .rdata file.
Have you managed to load the data successfully into your working environment?
If so, write.csv is the function you are looking for.
If not,
setwd("C:/Users/Zack-PC/Desktop/Study/Data Sets/pdCluster/")
signalList <- load("signalList.Rdata")
write.csv(signalList, "signalList.csv")
should do the trick.
If you would like to remove signalList from your working directory,
rm(signalList)
will accomplish this.
Note: changing your working directory isn't necessary, it just makes it easier to read in a comment I feel. You may also specify another path for saving your csv to within the second argument of write.csv.

Save the output of an r script including its commands

I want to save a part of my r script output including the commands into a text file. I know sink() but it does not include the commands or I could not find a specific option to do that.
Is there any possibility to capture the commands and its ouput within an r session. Simply write an Rmd or capture the output within the console is not the solution at the moment.
You are probably looking for the TeachingDemos package. Documentation can be found here.
Example:
library(TeachingDemos)
txtStart("test.txt")
# Your code
txtStop()
This should write both your command input and output to a file called test.txt.
If you're working interactively, here's one idea. It was this specific problem for which I created the sinkstart() function in the rite package. Basically, this creates a pop-up tcl/tk widget that you can write commands and output to. Here's a screenshot to give you a feel:
There are just two relevant functions: sinkstart() starts the sink; sinkstop() turns it off. You can toggle back and forth to selectively write to the widget. Then you can just save the contents with a right-click or a key shortcut.

questions about sink, in R

Lets say I want to use sink for writing to a file in R.
sink("outfile.txt")
cat("Line one.\n")
cat("Line two.")
sink()
question 1. I have seen people writing sink() at the end, why do we need this? Can something go wrong when we do not have this?
question 2. What is the best way to write many lines one by one to file with a for-loop, where you also need to format each line? That is I might need to have different number in each line, like in python I would use outfile.write("Line with number %.3f",1.231) etc.
Question 1:
The sink function redirects all text going to the stdout stream to the file handler you give to sink. This means that anything that would normally print out into your interactive R session, will now instead be written to the file in sink, in this case "outfile.txt".
When you call sink again without any arguments you are telling it to resume using stdout instead of "outfile.txt". So no, nothing will go wrong if you don't call sink() at the end, but you need to use it if you want to start seeing output again in your R session/
As #Roman has pointed out though, it is better to explicitly tell cat to output to the file. That way you get only what you want, and expect to see in the file, while still getting the rest ouf the output in the R session.
Question 2:
This also answers question two. R (as far as I am aware) does not have direct file handling like in python. Instead you can just use cat(..., file="outfile.txt") inside a for loop.

R Separate Results from Code

I am using R or starting to use R. I did some script using for loops, if... and I am happy with the results.
Now the issue I have is that in the console I would have all the line of codes (around 150 lines) when really I am just interested in 4 lines, my results.
Is there anyway to clean the console to see only some requested lines? and not all of the codes? If not I am thinking about saving them in a csv file and access the csv file to see the results of the script but it is not really efficient.
Thanks in advance
Xavier
I expect this to depend on how your 'results' are in the console, and whether all the rest is truly 'code'. Are these 4 lines the result of cat/print statements? Then you could look at ?sink to send the results to a file.
Another option is to store these results in a variable (e.g. a list), and at the end of all your calculations, print this list. after that it should be easy to do the separation.
You are writing code in a script editor and not in the console right? Another option would be to use source() on the script which will run the entire script but won't show in the console (only the output). RStudio (which I strongly recommend you use for R; http://rstudio.org/) has a "source this file" button or something like that.
But more importantly, getting R to clearly return the results is a big part of learning how to program in R. You want your scripts to be clear for others as well! Some solutions would be to make some code chunks a function or as Nick suggested storing results in a list.
For me, I would put your code into a function, which would effectively hide the code from the console as it is run, and store the results of the code into a variable and then save that to a file
foo <- function(x) {
result<-0
for(i in 1:length(x)){
result<-result+x[i]
}
return(result)
}
bar <- foo(x=c(2,3,4,5,4,3,2,3,4,5))
write.csv(bar, "resultfile.csv")

Resources