ayePete
ayePete

Reputation: 431

Remove extra row in printing to file

I'm attempting to print to file the output of a str_split operation as follows:

s <- t(unlist(str_split("foo_bar_0.5", "_"), use.names = FALSE))
write.csv(s, "test.csv", quote = FALSE, row.names = FALSE, col.names = FALSE)

With the row.names = FALSE argument, I was able to remove the row names. However, this code still writes an extra line with the column names to the file as follows:

V1,V2,V3
foo,bar,0.5

With the following warning:

Warning message:
In write.csv(s, "test.csv", quote = FALSE,  :
  attempt to set 'col.names' ignored

I want only the second line. Any ideas what I am doing wrong?

Upvotes: 1

Views: 69

Answers (1)

PKumar
PKumar

Reputation: 11128

Use write.table instead of write.csv :

write.table(s, "test.csv",sep=',', quote = FALSE, row.names = FALSE, col.names = FALSE)

write.table has two parameters like sep for putting the delimeter correctly in this case its comma, the other parameter is col.names which is a valid parameter, setting this to False should work for you.

Also as per documentation, if look for ?write.csv, for the ellipsis(...) , it says the following

... arguments to write.table: append, col.names, sep, dec and qmethod cannot be altered.

A more detailed explanation is also present in documentation which mentions the warning you are getting:

write.csv and write.csv2 provide convenience wrappers for writing CSV files. They set sep and dec (see below), qmethod = "double", and col.names to NA if row.names = TRUE (the default) and to TRUE otherwise.

write.csv uses "." for the decimal point and a comma for the separator.

write.csv2 uses a comma for the decimal point and a semicolon for the separator, the Excel convention for CSV files in some Western European locales.

These wrappers are deliberately inflexible: they are designed to ensure that the correct conventions are used to write a valid file. Attempts to change append, col.names, sep, dec or qmethod are ignored, with a warning.

Upvotes: 2

Related Questions