R Separate Results from Code - r

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")

Related

What is the standard R way to output results from a script?

I realize that a lot of work in R is done interactively where the output can immediately be seen. However, I usually want my scripts to be user-friendly and descriptive so I want output from my scripts to be minimally verbose.
I'm just still new in R and like to be able to transfer my work into a script for reuse. After searching around a bit on StackOverflow I came up with this result for my script:
# Display the results
paste("The number of houses is: ", numHouses, sep=" ")
This kind of output in Python could be:
print("The number of houses is %d", numHouses")
I would also REALLY prefer to end my sentences with a period, so append "." at the end of the output in R.
At the moment I do not need the data written to a file. I just want it written to the console. I'm using R Studio.
I like to use message because it can be easily suppressed in cases where the user doesn't want output. cat and print also work, but they don't seem to be handled as well from inside functions or loops. But cat can work on a stream of information, and print and message both take single character string inputs.
message(paste0("The number of houses is ", numHouses, "."))

Displaying png files from R into spotfire

I want to pass data from Spotfire to R and then display the plot constructed by R.
What is the best way to do this?
I’ve figured out the trick of putting images into Spotfire. It’s not hard if you follow these directions, but it’s done in a way very different from how you guess you would do it in Spotfire, and that’s why it took me awhile to figure out.
Here’s an overview of how to do it. You create a DocumentProperty which is a binary object, you write some Spotfire code that gives a value to that Document Property, and you display that binary object using a Spotfire Property Control of the “Label” type.
The confusing parts are that you DON’T use the Spotfire “Insert Image” tool at all, and that you DON’T use the filename generated inside the R code in Spotfire at all. Once you get used to the idea that the two most obvious ways you think you would approach the problem in Spotfire are entirely useless and wrong, you can make some progress.
I’ll leave out the spiderplot specifics because the code’s pretty long.
Here’s what you do.
1) Create a document Property in Spotfire of type “Binary”, e.g., “imageThatGoesBackToSpotfire”
2) You write some R code that generates an image and writes it to a file:
# get a temporary directory name on the local machine. You wouldn’t need to do this is you were just
# going to run it on your own, but you need to do it if you intend to let anybody else run it on their own machine.
tempfilebase = tempfile()
# take the tempfilebase and prepend it to a filename.
myFilename<-“someFileName.jpg”
myFullFilename <- paste(tempfilebase,myFilename,sep="")
#open a jpeg
jpeg(filename=myFullFileName)
# generate the image, however you normally would in R
plot(input)
# close the file
dev.off
# open a connection to that file.
myConnection<-file(myFullFileName,open=”rb”)
imageThatGoesBackToSpotfire<- data.frame(r=readBin(myConnection, what="raw", n=(file.info(myFullFileName)$size)))
close(myConnection)
3) Run your R script, above. Select some columns that are the “input” to the plot, and make the R script return outputs to the “imageThatGoesBackToSpotfire” DocumentProperties.
4) Create a text area in Spotfire.
5) Insert a Property Control into the text area of type “label”. (Click on the icon that’s circled in the picture below). This opens a dialog,
You need to register a data function with inputs and outputs, and the specific PNG data needs to be returned as a binary label.
Some details: http://spotfire.tibco.com/tips/2014/02/25/dynamically-displaying-images-in-a-text-area/

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.

in R , how to get the output to a file as well as on console at the same time?

I want only the output not the commands, and I want to see the output on the console at the same time.
I tried sink and capture.output , but tried to work through the examples but I can accomplish only one of the task i.e. either to console or to a file.
I am new to R, and was thinking whether there is a function that can help me see the output on the console and save it to a text file as well?
Do sink(file="file.txt", split=TRUE).

How to save a function as new R script?

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.

Resources