问题是您的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)
更新为避免对第一列名称进行硬编码,加载时不能丢失它:
# 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 列。