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.
Related
more a tip question that can save lots of time in many cases. I have a script.R file which I try to save and get the error:
Not all of the characters in ~/folder/script.R could be encoded using ASCII. To save using a different encoding, choose "File | Save with Encoding..." from the main menu.
I was working on this file for months and today I was editing like crazy my code and got this error for the first time, so obviously I inserted a character that can not be encoded while I was working today.
My question is, can I track and find this specific character and where exactly in the document is?
There are about 1000 lines in my code and it's almost impossible to manually search it.
Use tools::showNonASCIIfile() to spot the non-ascii.
Let me suggest two slight improvements this.
Process:
Save your file using a different encoding (eg UTF-8)
set a variable 'f' to the name of that file. something like this f <- yourpath\\yourfile.R
Then use tools::showNonASCIIfile(f) to display the faulty characters.
Something to check:
I have a Markdown file which I run to output to Word document (not important).
Some of the packages I used to initialise overload previous functions. I have found that the warning messages sometimes have nonASCII characters and this seems to have caused this message for me - some fault put all that output at the end of the file and I had to delete it anyway!
Check where characters are coming back from Warnings!
Cheers
Expanding the accepted answer with this answer to another question, to check for offending characters in the script currently open in RStudio, you can use this:
tools::showNonASCIIfile(rstudioapi::getSourceEditorContext()$path)
I'm currently implementing a tool in R and I got stucked with a problem. I looked already in the forums and didn't found anything.
I have many .csv files, which are somehow correlated with each other. The problem is I don't know yet how (this depends on the input of the user of the tool). Now I would like to read in a csv-file, that contains an arbitrary function f, e.g. f: a=b+max(c,d), and then the inputs, e.g. a="Final Sheet", b="Sheet1", c="Sheet2", d="Sheet3". (Maybe I didn't explained it very well, then I will upload a picture).
Now my question is, can I somehow read that csv file in, such that I can later use the function f in the programm? (Of course the given function has to be common in R).
I hope you understand my problem and I would appreciate any help or idea!!
I would not combine data files with R source. Much easier to keep them separate. You put your functions in separate script files and then source() them as needed, and load your data with read.csv() etc.
"Keep It Simple" :-)
I am sure there's a contorted way of reading in the source code of a function from a text file and then eval() it somehow -- but I am not sure it would be worth the effort.
I am just learning R, so this might be a simple question.
I have a bunch of code that I want to run IF a certain file path that was generated earlier in the code exists. So...
1.A path is created
2.If the path exists, then the rest of the code should run
This is what this portion of the code looks like:
label_file=paste(label_folder,"Files/",as.matrix(babble_data)[n,3],label_extension,sep="")
if (file.exists(label_file){...
It is running without giving me any errors, but it is treating EVERY file path (even the ones that DO exist) like the don't exist.
Is my syntax incorrect? All the examples I can find look like this, so I have no idea why it isn't working as it is supposed to. Any idea? Thanks.
You are missing a closing round bracket in the if statement before the curly bracket. This can have all possible side effects, although a code parsing error is the most probable one.
Additionally, as.matrix(babble_data)[n,3] can produce a vector of results, so paste can produce a vector of filenames and if (file.exists( would fail.
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.
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")