+4 votes
in Programming Languages by (5.2k points)
I want to write several lines of text data to a TSV file. But I do find an easy way like Python or other languages have. What is the syntax in R to write data to a file?

1 Answer

0 votes
by (33.0k points)

There are several ways to write data to a TSV file in R. If you have used Python in past, you may not find similar functions in R. However, it's not difficult to write data to a file.

In the following example, I am creating a TSV file "output.tsv". The file has a header with 3 columns and they are separated by a tab. In the write() function, you need to specify the record you want to write to the file, the name of the file, set append to TRUE, and separator "\n". "\n" will make sure that the next record is written to a new line.

If you have non-text records to write, you can convert them to characters using as.character() method. You can use the "for" loop to write several lines to the file.

fileout <- "output.tsv"
hdr = "col1\t col2\t col3"
write(hdr, file=fileout, append=T, sep= "\n")
line = paste(as.character(v1), as.character(v2), as.character(v3), sep = "\t")
write(line, file=fileout, append=T, sep= "\n")

Related questions