Frage

I can use write.table function to create an output data from a data.frame:

> write.table(head(cars), sep = "|", row.names=FALSE)
"speed"|"dist"
4|2
4|10
7|4
7|22
8|16
9|10

How can I create my own write.table function which creates an output like this (header with double pipes and data with preceding and succeeding pipes)?:

||"speed"||"dist"||
|4|2|
|4|10|
|7|4|
|7|22|
|8|16|
|9|10|
War es hilfreich?

Lösung

write.table can get you part of the way, but you will still need to do some fiddling around to get things to work just as you want.

Here's an example:

x <- capture.output(
  write.table(head(cars), sep = "|", row.names = FALSE, eol = "|\n"))
x2 <- paste0("|", x)
x2[1] <- gsub("|", "||", x2[1], fixed=TRUE)
cat(x2, sep = "\n")
# ||"speed"||"dist"||
# |4|2|
# |4|10|
# |7|4|
# |7|22|
# |8|16|
# |9|10|

As a function, I guess in its most basic form it could look something like:

write.myOut <- function(inDF, outputFile) {
  x <- capture.output(
    write.table(inDF, sep = "|", row.names = FALSE, eol = "|\n"))
  x <- paste0("|", x)
  x[1] <- gsub("|", "||", x[1], fixed=TRUE)
  cat(x, sep = "\n", file=outputFile)
}

Andere Tipps

I don't think that it is possible with write.table. Here is a workaround:

# function for formatting a row
rowFun <- function(x, sep = "|") {
  paste0(sep, paste(x, collapse = sep), sep)
}

# create strings
rows <- apply(head(cars), 1, rowFun)
header <- rowFun(gsub("^|(.)$", "\\1\"", names(head(cars))), sep = "||")

# combine header and row strings
vec <- c(header, rows)

# write the vector
write(vec, sep = "\n", file = "myfile.sep")

The resulting file:

||"speed"||"dist"||
|4|2|
|4|10|
|7|4|
|7|22|
|8|16|
|9|10|
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top