1

我有一个类似于这种格式的 lagre 数据框:

line1
line2<tab>value1

当它在 R 中使用 read.csv 读取时,它被强制进入数据帧,如下所示:

V1<tab>V2
line1<tab>NA
line2<tab>value1

我可以用空字符串替换 NA,但是当我使用 write.table 编写时,我在输出文件的第 1 行之后得到一个制表符和空白空间。

如何使输出与输入的格式相同,即删除尾随的制表符空格

附加示例文件:

#Sample SGA file format
@HD VN:1.0.0    IA:NA
@PL NM:TEST
1   1   705 50947   YDL185W YOR202W -   -   -
1   2   377 50947   YDL185W YOR202W -   -   -
1   3   317 50947   YDL185W YOR202W -   -   -
...
@SP CF:ORF,IGNA
TEST    1
TEST2   1

头(输入(数据))

structure(list(V1 = c("#Sample SGA file format", "@HD", 
"@PL", "1", "1", "1"), V2 = c("", "VN:1.0.0", "NM:TEST", "1", 
"2", "3"), V3 = c("", "IA:NA", "", "705", "377", "317"), V4 = c(NA, 
NA, NA, 50947L, 50947L, 50947L), V5 = c("", "", "", "YDL185W", 
"YDL185W", "YDL185W"), V6 = c("", "", "", "YOR202W", "YOR202W", 
"YOR202W"), V7 = c("", "", "", "-", "-", "-"), V8 = c("", "", 
"", "-", "-", "-"), V9 = c("", "", "", "-", "-", "-")), .Names = c("V1", 
"V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9"), row.names = c(NA, 
6L), class = "data.frame")

和str(数据)

'data.frame':   1541 obs. of  9 variables:
 $ V1: chr  "#Sample SGA file format" "@HD" "@PL" "1" ...
 $ V2: chr  "" "VN:1.0.0" "NM:TEST" "1" ...
 $ V3: chr  "" "IA:NA" "" "705" ...
 $ V4: int  NA NA NA 50947 50947 50947 50947 50947 50947 50947 ...
 $ V5: chr  "" "" "" "YDL185W" ...
 $ V6: chr  "" "" "" "YOR202W" ...
 $ V7: chr  "" "" "" "-" ...
 $ V8: chr  "" "" "" "-" ...
 $ V9: chr  "" "" "" "-" ...
4

4 回答 4

4

我赌一个猜测。听起来你可以做两件事之一。

首先,你可以使用

data[is.na(data)] <- ''
library(stringr)
write.table(str_trim(apply(data, 1, paste, collapse='\t')),
            'fileout.tsv',
            row.names=FALSE)

或者您可以使用命令行实用程序,例如sed从文件中删除尾随空格:

sed -e :a -e 's/^.\{1,77\}$/ & /;ta'
于 2012-08-30T16:28:19.127 回答
3

这是非常令人费解的,但在这里。

  1. 将 line1 作为标题读取read.csvfoo <- read.csv("input.csv")

  2. 使用 仅写第一列名称writewrite(colnames(foo)[1],"out/output.csv")

  3. append最后,使用和不使用列名来编写表的其余部分:write.table(foo,"output.csv",sep=",",row.names=F,col.names=F,append=T,quote=F)

这应该会为您提供与输入文件相同格式的输出文件。

于 2012-08-29T21:18:36.623 回答
3

这类似于贾斯汀的回答,使用正则表达式。

cn <- file("output.txt",open="w") #opens write connection to file
writeLines(paste(names(data),collapse="\t"),con=cn) #writes header
#converts data frame into vector of character, with fields separated by tabs
to.print <- apply(data,1,paste,collapse="\t") 
to.print <- gsub("\\tNA$","",to.print) #deletes trailing <tab>NA
writeLines(to.print,con=cn) #writes data frame rows
close(cn)
于 2012-08-31T18:52:55.823 回答
-1

如果你想read.table表现得完全一样read.csv,你需要做的就是使参数相同

read.table(file, header = TRUE, sep = ",", quote="\"", dec=".",
     fill = TRUE, comment.char="")
于 2012-08-29T21:29:04.067 回答