2014-01-08 111 views
0

我可以使用write.table函数从data.frame创建的输出数据:如何创建自定义write.table函数?

> 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| 
+0

看一看'write.table'的代码。你想要这个函数来写入文件或在屏幕上显示吗? –

+0

我希望它写入文件,例如write.table(head(cars),sep =“|”,file =“myfile.sep”) – jrara

+0

你能解释一下'||“speed”||“dist”||'(我明白第一个双管道是数据中有一列额外的行号,但不包含在标题中)。但其他两个'||'的功能是什么?所以你的头里有6个分隔符,但数据只有4个?否则,就像'write.pipetable < - function(obj,file)write.table(obj,file,sep =“|”)'是可能的答案。 (另外,如果你真的需要额外的分隔符和行首,你可以在左侧和右侧添加空列,并使用'na =“”' - – lebatsnok

回答

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

你想要什么如果数据值的头部包含“|”字符,或者如果头部值包含一个“”字符,就会发生这种情况 –

+0

@RichieCotton只有OP可以回答这个问题,使用提供的代码,'|'和''' s将被保存。 –

相关问题