简体   繁体   English

如何使用write.table在第一行写一个特殊字符

[英]How to write a special character in first line with write.table

I have a dataset ped which I want to write into a tab separated file. 我有一个数据集ped ,我想将其写入制表符分隔的文件中。 However the header needs to start with a hash ( # ) sign (due to the demands of the program who should read the file. How do I put the hash sign in there? 但是,标头需要以井号( # )开头(由于程序要求读取文件的人。如何将井号放在其中?

ped <- ped [,c('FAM_ID','IND_ID','FAT_ID','MOT_ID','SEX','DISEASE','RR','AGE')]
setwd(proj.dir)
write.table(ped, "DB/asymmetry.ped", sep="\t", row.names = FALSE, quote = FALSE)

You might try: 您可以尝试:

cat("#", file = "DB/asymmetry.ped")
write.table(ped, "DB/asymmetry.ped", sep="\t", row.names = FALSE, quote = FALSE,
            append = TRUE)

Note, you will get a warning message from write.table as this is the default behaviour: 注意,您将从write.table收到警告消息,因为这是默认行为:

## somewhere inside `write.table`:
if (!is.null(col.names)) {
        if (append) 
            warning("appending column names to file")

but it causes no harm. 但不会造成伤害。


Another possible way, is to append an "#" to your first column name, then use write.table as usual (with quote = FALSE ): 另一种可能的方法是在第一个列名后附加"#" ,然后照常使用write.table (带有quote = FALSE ):

ped <- ped [,c('FAM_ID','IND_ID','FAT_ID','MOT_ID','SEX','DISEASE','RR','AGE')]
NAMES <- names(ped)
NAMES[1] <- paste0("#", NAMES[1])
setwd(proj.dir)
write.table(ped, "DB/asymmetry.ped", sep="\t", row.names = FALSE, quote = FALSE,
            col.names = NAMES)

I would recommend this way. 我会推荐这种方式。 Let's have a test: 让我们进行测试:

x <- trees[1:3, ]  ## use built-in dataset `trees`
NAMES <- names(x)
NAMES[1] <- paste0("#", NAMES[1])
## write to screen (stdout) for inspection
write.table(x, row.names = FALSE, col.names = NAMES, quote = FALSE)

#Girth Height Volume
8.3 70 10.3
8.6 65 10.3
8.8 63 10.2

In case you want to add an # at the start of every line / row, you can append a "#" column as the first column: 如果要在每行/每行的开头添加# ,则可以在第一列后附加"#"列:

ped <- cbind.data.frame("#" = "#", ped[,c('FAM_ID','IND_ID','FAT_ID','MOT_ID','SEX','DISEASE','RR','AGE')])
setwd(proj.dir)
write.table(ped, "DB/asymmetry.ped", sep="\t", row.names = FALSE, quote = FALSE)

Again, let's have a test: 再次,让我们进行测试:

x <- cbind.data.frame("#" = "#", trees[1:3, ])
## write to screen (stdout) for inspection
write.table(x, row.names = FALSE, quote = FALSE)

# Girth Height Volume
# 8.3 70 10.3
# 8.6 65 10.3
# 8.8 63 10.2

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

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