如何创建自定义write.table函数?

时间:2014-01-08 12:28:16

标签: r write.table

我可以使用write.table函数从data.frame创建输出数据:

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

如何创建自己的write.table函数,该函数创建一个这样的输出(带有双管道的标题和带有前后管道的数据)?:

||"speed"||"dist"||
|4|2|
|4|10|
|7|4|
|7|22|
|8|16|
|9|10|

2 个答案:

答案 0 :(得分: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|

答案 1 :(得分: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)
}