1
votes

I have written a function that allows me to take four columns of data from the clipboard, split it, add an extra column, recombine it, and export it as a text file.

xyztoinp <- function(x) {
    x <- read.table(file="clipboard") 
    a <- x[,-1] 
    b <- x[,1]
    c <- ifelse(b == "C", 6,
    ifelse (b == "O", 8,ifelse (b == "H", 1, 3)))
    x <- cbind(b,c,a)
    write.table(x, file="IRCoutput", quote = FALSE,
    sep = "\t", row.names = FALSE, col.names = FALSE)
}

I have two questions:-

Is it possible to create a file that has the table that I've created with this function such that the table is pasted into the middle of some text?

Eg

text_text_text_text_text_text_text_
text_text_text_text_text_text_text_

Neatly formated table

text_text_text_text_text_text_text_
text_text_text_text_text_text_text_

Secondly, I tried to modify the function so that it would take a file name as a variable; ie, xyztoinp <- function(x, NewFileName) {

etc... But this didn't produce an output with the new file name; does anyone know how this is done?

Here is my working code,

xyztoinp <- function(x) {
     x <- read.table(file="clipboard")
     a <- x[,-1]
     b <- x[,1]
     c <- ifelse(b == "C", 6,
     ifelse (b == "O", 8,
     ifelse (b == "H", 1, 3)))
     x <- cbind(b,c,a)
     zz <- file("NewFile.inp", "w")
     cat("text",      " text",
     "text",
     "",
     "text",
     "text",
     "text", file = zz, sep = "\n")
     write.table(x, file=zz, quote = FALSE,
     sep = "\t", row.names = FALSE, col.names = FALSE)
     cat("text",file=zz)
     close(zz)
}

thanks all, esp @Greg. ps It wasn't possible to vary the filename in the function but I'm happy with the above.

1
a) Welcome to SO. b) Please learn to format your question. c) See the R Input/Output manual that came with your installation of R.Dirk Eddelbuettel

1 Answers

1
votes

The general reason why people want tables (or graphs, or output, or ...) insterted into text is to create an automatic report of some sort (if this is not your case then please give more detail so we can answer the actual question).

To create automated reports with nicely formated tables (and other things) the best approach is to create a template and process it to create the report. Look at the knitr package for details on doing this (you can also use the odfweave package or the sweave function or others, but knitr is probably the most general).

Another option if you don't want to precreate the report template is the pander package.

Switching to pander or knitr may take care of your second question as well, but if not then we will need to see what you tried and what happened to know why it did not work and how to help.