Adding items to txt output in the same file from - r

I would like to printout to the same txt (outfile.txt) file items one after the other.
For instance, first I would like to print to outfile.txt a dataframe - u. Afterwards, a written message 'hello' and finally a summary of model.
How can I do it? Is sink(outfile.txt) is appropriate for this case?

It is generally a very bad idea to mix data in the same file. I advise against it in the strongest terms: it makes the data file next to unusable for other programs.
That said, most functions to save data have an append argument. You can set this to TRUE to append to an existing file rather than overwriting its contents. No need for sink.
Where you do need sink (or equivalent) is when you want to write contents formatted in the same way as it’s written on the console. This, for instance, is the case for summary.
Here’s an example similar to your requirements:
filename = 'test.txt'
write.table(head(cars), filename, quote = FALSE, col.names = NA)
cat('\nHello\n\n', file = filename, append = TRUE)
capture.output(print(summary(cars)), file = filename, append = TRUE)
Rather than sink, this uses capture.output, which is a convenience wrapper around sink.

Related

Specify path in write.csv function

I have a simple syntax question: Is there a way to specify the path in which to write a csv file within the .csv function itself?
I always do the following:
setwd("C:/Users/user/Desktop")
write.csv(dt, "my_file.csv", row.names = F)
However, I would like to skip the setwd() line and include it directly in the write.csv() function. I can't find a path setting in the write.csv documentation file. Is it possible to do this exclusively in write.csv without using write.table() or having to download any packages?
I am writing around 300 .csv files in a script that runs auomatically everyday. The loop runs slower when using write.table() than when using write.csv(). The whole reason I want to include the path in the write.csv() function is to see if I can decrease the time it takes to execute any further.
I typically set my "out" path in the beginning and then just use paste() to create the full filename to save to.
path_out = 'C:\\Users\\user\\Desktop\\'
fileName = paste(path_out, 'my_file.csv',sep = '')
write.csv(dt,fileName)
or all within write.csv()
path_out = 'C:\\Users\\user\\Desktop\\'
write.csv(dt,paste(path_out,'my_file.csv',sep = ''))
There is a specialized function for this: file.path:
path <- "C:/Users/user/Desktop"
write.csv(dt, file.path(path, "my_file.csv"), row.names=FALSE)
Quoting from ?file.path, its purpose is:
Construct the path to a file from components in a platform-independent way.
Some of the few things it does automatically (and paste doesn't):
Using a platform-specific path separator
Adding the path separator between path and filename (if it's not already there)
Another way might be to build a wrapper function around the write.csv function and pass the arguments of the write.csv function in your wrapper function.
write_csv_path <- function(dt,filename,sep,path){
write.csv(dt,paste0(path,filename,sep = sep))
}
Example
write_csv_path(dt = mtcars,filename = "file.csv",sep = "",path = ".\\")
In my case this works fine,
create a folder -> mmult.datas
copy its directory-> C:/Users/seyma/TP/tp.R/tp.R5 - Copy
give a name of your .csv -> df.Bench.csv
do not forget the write your data.frame -> df
write.csv(df, file ="C:/Users/seyma/TP/tp.R/tp.R5 - Copy/mmult.datas/df.Bench.csv")
for more you can check the link

Strings containing an accent do not appear

I'm currently building a shiny application that needs to be translated in different languages. I have the whole structure but I'm struggling into getting values such as "Validació" that contain accents.
The structure I've followed is the following:
I have a dictionary that is simply a csv with the translation where
there's a key and then each language. The structure of this dictionary is the following:
key, cat, en
"selecció", "selecció", "Selection"
"Diferències","Diferències", "Differences"
"Descarregar","Descarregar", "Download"
"Diagnòstics","Diagnòstics", "Diagnoses"
I have a script that once the dictionary.csv is modified, generates a .bin file that later will be loaded in the code.
In strings.R I have all the strings that will appear on the code and I use a function to translate the current language to the one I want. The function is the following:
Code:
tr <- function(text){
sapply(text, function(s) translation[[s]][["cat"]], USE.NAMES=F)
}
When I translate something, since I am doing in another file, I assign it to another variable something like:
str_seleccio <- tr('Selecció)
The problem I'm facing is that for example if we translate 'Selecció' would be according to this function, tr('Selecció') and provides a correct answer if I execute it in the RStudio terminal but when I do it in the Shiny application, appears to me as a NULL. If the word I translate has no accents such as "Hello", tr("Hello") provides me a correct answer in the Shiny application and I can see it throught the code.
So mainly tr(word) gets the correct value but when assigning it "loses the value" so I'm a bit lost how to do it.
I know that you can do something like Encoding(str_seleccio) <- "UTF-8" but in this case is not working. In case of plain words it used to do but since when I asssign it, gets NULL is not working.
Any idea? Any suggestion? What I would like is to add something to tr function
The main idea comes from this repository that if you can take a look is the simplest version you can do, but (s)he has problem with utf-8 also.
https://github.com/chrislad/multilingualShinyApp
As in http://shiny.rstudio.com/articles/unicode.html suggested (re)save all files with UTF-8 encoding.
Additionaly change within updateTranslation.R:
translationContent <- read.delim("dictionary.csv", header = TRUE, sep = "\t", as.is = TRUE)
to:
translationContent <- read.delim("dictionary.csv", header = TRUE, sep = "\t", as.is = TRUE, fileEncoding = "UTF-8").
Warning, when you (re)save ui.R, your "c-cedilla" might get destroyed. Just re-insert it, in case it happens.
Happy easter :)

Different number of lines when loading a file into R

I have a .txt file with one column consisting of 1040 lines (including a header). However, when loading it into R using the read.table() command, it's showing 1044 lines (including a header).
The snippet of the file looks like
L*H
no
H*L
no
no
no
H*L
no
Might it be an issue with R?
When opened in Excel it doesn't show any errors as well.
EDIT
The problem was that R read a line like L + H* as three separated lines L + H*.
I used
table <- read.table(file.choose(), header=T, encoding="UTF-8", quote="\n")
You can try readLines() to see how many lines are there in your file. And feel free to use read.csv() to import it again to see it gets the expected return. Sometimes, the file may be parsed differently due to extra quote, extra return, and potentially some other things.
possible import steps:
look at your data with text editor or readLines() to figure out the delimiter and file type
Determine an import method (type read and press tab, you will see the import functions for import. Also check out readr.)
customize your argument. For example, if you have a header or not, or if you want to skip the first n lines.
Look at the data again in R with View(head(data)) or View(tail(data)). And determine if you need to repeat step 2,3,4
Based on the data you have provided, try using sep = "\n". By using sep = "\n" we ensure that each line is read as a single column value. Additionally, quote does not need to be used at all. There is no header in your example data, so I would remove that argument as well.
All that said, the following code should get the job done.
table <- read.table(file.choose(), sep = "\n")

R: How to use append = TRUE but also delete existing file

I have a for loop that loops through files and creates a giant CSV file by appending all the different data frames.
For this to work I have used
append= TRUE
However, since I used that, if i run the loop again, it just appends the same thing to the file before.
I was wondering if there is a way I can tell the code to delete any file with that name before running the loop, so it does not append to old data.
This is the write.table code I have right now
write.table(dat, "data.csv", append = TRUE, sep = ",", col.names=!file.exists("data.csv"))
How about this in front of the loop?
if (file.exists("[yourfilename]"){
unlink("[yourfilename]")
}

Reading a file in, then writing out a file with similar name in R

In R, I would like to read in data from a file, then do a bunch of stuff, then write out data to another file. I can do that. But I'd like to have the two files have similar names automatically.
e.g. if I create a file params1.R I can read it in with
source("c:\\personal\\consults\\ElwinWu\\params1.R")
then do a lot of stuff
then write out a resulting table with write.table and a filename similar to above, except with output1 instead of params1.
But I will be doing this with many different params files, and I can foresee making careless mistakes of not changing the output file to match the params file. Is there a way to automate this?
That is, set the number for output to match the number for params?
thanks
Peter
If your source file always contains "params" which you want to change to "output" then you can easilly do this with gsub:
source(file <- "c:\\personal\\consults\\ElwinWu\\params1.R")
### some stuff
write.table(youroutput, gsub("params","output",file) )
# Will write in "c:\\personal\\consults\\ElwinWu\\output1.R"
Edit:
Or to get .txt as filetype:
write.table(youroutput, gsub(".R",".txt",gsub("params","output",file)))
# Will output in c:\\personal\\consults\\ElwinWu\\output1.txt"
Edit2:
And a loop for 20 param files then would be:
n <- 20 # number of files
for (i in 1:n)
{
source(file <- paste("c:\\personal\\consults\\ElwinWu\\params",i,".R",sep=""))
### some stuff
write(youroutput, gsub(".R",".txt",gsub("params","output",file)))
}
If the idea is just to make sure that all the outputs go in the same directory as the input then try this:
source(file <- "c:\\personal\\consults\\ElwinWu\\params1.R")
old.dir <- setwd(dirname(file))
write.table(...whatever..., file = "output1.dat")
write.table(...whatever..., file = "output2.dat")
setwd(old.dir)
If you don't need to preserve the initial directory you can omit the last line.

Resources