简体   繁体   中英

R read.table <-> write.table

In 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?

write.table(d, ?)

I give you one example input file:

one two
1   2

The separator is "\\t". What are the write.table parameters that would write the exact same output file after reading it with read.table?

Thank you, Gregor

The problem is that your read.table used column 1 as row.names so it lost its column name ("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". Then you simply have to disable the use of row.names and quotes, and specify the separator:

# 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:

# 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.

write.table(d,"filename")

you have to specify which file extension you want to use. Hope it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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