简体   繁体   English

R read.table <->写表

[英]R read.table <-> write.table

In R: 在R中:

d=read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)

What is the command to write back the exact same file from d? 从d写回完全相同的文件的命令是什么?

write.table(d, ?)

I give you one example input file: 我给您一个示例输入文件:

one two
1   2

The separator is "\\t". 分隔符为“ \\ t”。 What are the write.table parameters that would write the exact same output file after reading it with read.table? 用read.table读取完全相同的输出文件后,write.table参数是什么?

Thank you, Gregor 谢谢格雷戈尔

The problem is that your read.table used column 1 as row.names so it lost its column name ("one"). 问题是您的read.table将列1用作row.names因此丢失了列名(“ one”)。 When you write it out, you have to do something special to get the "one" name back. 写出来时,必须做一些特殊的事情才能重新获得“一个”名称。

cbind(one=row.names(d), d) will add the row.names as a column with the name "one". cbind(one=row.names(d), d)将row.names添加为名称为“ one”的列。 Then you simply have to disable the use of row.names and quotes, and specify the separator: 然后,您只需要禁用row.names和引号,并指定分隔符即可:

# Create the test file
filename <- "test.txt"
filename2 <- "test2.txt"
cat("one\ttwo\n1\t2\n", file=filename)

# read it in
d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)

# write it out again
write.table(cbind(one=row.names(d), d), filename2, row.names=FALSE, sep="\t", quote=FALSE)

# Ensure they are the same:
identical(readLines(filename), readLines(filename2)) # TRUE

readLines(filename)
readLines(filename2)

UPDATE To avoid hard-coding the first column name, you mustn't lose it when loading: UPDATE为避免对第一列名称进行硬编码,加载时一定不要丢失它:

# Read the data without any row.names
d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = NULL)
# Then use the first column as row.names (but keeping the first column!)
row.names(d) <- d[[1]]
d
#  one two
#1   1   2        

# Now you can simply write it out...
write.table(d, filename2, row.names=FALSE, sep="\t", quote=FALSE)

# Ensure they are the same:
identical(readLines(filename), readLines(filename2)) # TRUE

You could of course still remove column 1 if you keep the name of it around and use it as in the first example. 当然,如果您保留第1列的名称并像第一个示例一样使用它,则仍然可以删除它。

write.table(d,"filename")

you have to specify which file extension you want to use. 您必须指定要使用的文件扩展名。 Hope it works. 希望它能工作。

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

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