简体   繁体   English

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

[英]How to create a custom write.table function?

I can use write.table function to create an output data from a data.frame: 我可以使用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

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)?: 如何创建我自己的write.table函数,该函数创建一个这样的输出(带有双管道的标题和带有前后管道的数据)?:

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

I don't think that it is possible with write.table . 我不认为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|

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. write.table可以让你成为一部分,但你仍然需要做一些摆弄,让事情按照你的意愿运作。

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM