繁体   English   中英

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

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

我可以使用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|

我不认为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|

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

暂无
暂无

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

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