繁体   English   中英

R read.table <->写表

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

在R中:

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

从d写回完全相同的文件的命令是什么?

write.table(d, ?)

我给您一个示例输入文件:

one two
1   2

分隔符为“ \\ t”。 用read.table读取完全相同的输出文件后,write.table参数是什么?

谢谢格雷戈尔

问题是您的read.table将列1用作row.names因此丢失了列名(“ one”)。 写出来时,必须做一些特殊的事情才能重新获得“一个”名称。

cbind(one=row.names(d), d)将row.names添加为名称为“ one”的列。 然后,您只需要禁用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为避免对第一列名称进行硬编码,加载时一定不要丢失它:

# 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

当然,如果您保留第1列的名称并像第一个示例一样使用它,则仍然可以删除它。

write.table(d,"filename")

您必须指定要使用的文件扩展名。 希望它能工作。

暂无
暂无

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

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