0

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|
4

2 回答 2

1

我不认为这是可能的write.table。这是一种解决方法:

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

结果文件:

||"speed"||"dist"||
|4|2|
|4|10|
|7|4|
|7|22|
|8|16|
|9|10|
于 2014-01-08T12:46:31.557 回答
1

write.table可以让你参与其中,但你仍然需要做一些摆弄才能让事情按照你的意愿工作。

这是一个例子:

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|

作为一个函数,我猜它最基本的形式可能类似于:

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)
}
于 2014-01-08T13:25:15.760 回答