r - 使用 write.table 时避免在列名和行名中使用引号

标签 r double-quotes write.table

这个问题在这里已经有了答案:





Delete "" from csv values and change column names when writing to a CSV

(1 个回答)


3年前关闭。




我在名为“data.txt”的文件中有以下数据:

pid      1     2     4     15      18       20
1_at   100   200   89    189     299      788
2_at     8    78   33     89      90       99
3_xt   300    45   53    234      89       34
4_dx    49    34   88      8       9       15

数据由制表符分隔。

现在我想提取该表上的一些列,基于名为“vector.csv”的csv文件的信息,该向量得到以下数据:
18,1,4,20

所以我想以一个修改过的文件“datamod.txt”结束,这些文件用标签分隔,这将是:
pid      18       1     4      20
1_at   299     100    89     788
2_at    90       8    33      99
3_xt    89     300    53      34
4_dx     9      49    88      15

我在一些帮助下制作了以下代码:
fileName="vector.csv"
con=file(fileName,open="r")
controlfile<-readLines(con)
controls<-controlfile[1]
controlins<-controlfile[2]
test<-paste("pid",controlins,sep=",")
test2<-c(strsplit(test,","))
test3<-c(do.call("rbind",test2)) 
df<-read.table("data.txt",header=T,check.names=F)
CC <- sapply(df, class)
CC[!names(CC) %in% test3] <- "NULL"
df <- read.table("data.txt", header=T, colClasses=CC,check.names=F)
df<-df[,test3]
write.table(df,"datamod.txt",row.names=FALSE,sep="\t")

我遇到的问题是我生成的文件具有以下格式:
"pid"      "18"       "1"     "4"      "20"
"1_at"   299         100      89       788
"2_at"    90           8      33        99
"3_xt"    89         300      53        34
"4_dx"     9          49      88        15

我的问题是如何避免出现在我保存的文件中的那些引号“”,以便数据看起来像我想要的那样。

有什么帮助吗?

谢谢

最佳答案

引用 write.table 的帮助文件
quote

a logical value (TRUE or FALSE) or a numeric vector. If TRUE, any character or factor columns will be surrounded by double quotes. If a numeric vector, its elements are taken as the indices of columns to quote. In both cases, row and column names are quoted if they are written. If FALSE, nothing is quoted.



所以
write.table(df,"datamod.txt",row.names=FALSE,sep="\t", quote = FALSE)

应该很好用。

关于r - 使用 write.table 时避免在列名和行名中使用引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846433/

相关文章:

r - ggplot 图例标签内的希腊字母、符号和换行符

regex - 如何使用grep匹配双引号

r - 省略txt文件的最后一个行结束符(R中的write.table)

python - 使用 Python 将包含双引号的参数传递给子进程

javascript - ' ' 和 ""以及没有引号在 Javascript 中是什么意思?

r - 在R中输出文件而不覆盖

r - 如何在 R 中使用 testthat 处理 "example files"?

rCharts rNVD3 工具提示自定义

r - 按年份对 data.table 结果进行分组的有效方法

html - knitr、R Markdown 和 xtable : xtable tables within HTML table