Anish
Anish

Reputation: 1950

Undesired output from write.table() function in R

I have a csv file which i loaded into R using read.csv and performed some operation. And, now I need to write it back to csv format. However the problem is that, the write.table() function does not produces the require output.

Initial Data:

id,name,Households,Population,Total Male,Total Female
0,Nepal,5427302,26494504,12849041,13645463
1,Taplejung,26509,127461,60552,66909
2,Panchthar,41196,191817,90186,101631
3,Ilam,64502,290254,141126,149128
4,Jhapa,184552,812650,385096,427554

Final Output with write.table()

"id","name","Households","Population","SexRatio"
"1",0,"Nepal",5427302,26494504,94.1634666408901
"2",1,"Taplejung",26509,127461,90.499036004125
"3",2,"Panchthar",41196,191817,88.7386722555126
"4",3,"Ilam",64502,290254,94.634139799367
"5",4,"Jhapa",184552,812650,90.0695584651295

how can I get the final output in input format?

Upvotes: 0

Views: 148

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I am guessing that your main complaint is about the "row names" that have been appended to the output and the quotes around all the strings.

If that is the case, look into the arguments row.names and quote in write.table() (and thus, write.csv()) and set them to FALSE when you are writing your files.

Here's an example, assuming that your data in R is called inData.

First, we'll write inData to a file with the default arguments to write.csv. Note the row names and the quoted strings.

write.csv(inData, file = "oldfile.csv")

cat(readLines("oldfile.csv"), sep="\n")
# "","id","name","Households","Population","Total.Male","Total.Female"
# "1",0,"Nepal",5427302,26494504,12849041,13645463
# "2",1,"Taplejung",26509,127461,60552,66909
# "3",2,"Panchthar",41196,191817,90186,101631
# "4",3,"Ilam",64502,290254,141126,149128
# "5",4,"Jhapa",184552,812650,385096,427554

Here's the same thing with inData being written with the arguments I've mentioned set to FALSE:

write.csv(inData, file = "newfile.csv", 
          row.names = FALSE, quote = FALSE)

cat(readLines("newfile.csv"), sep="\n")
# id,name,Households,Population,Total.Male,Total.Female
# 0,Nepal,5427302,26494504,12849041,13645463
# 1,Taplejung,26509,127461,60552,66909
# 2,Panchthar,41196,191817,90186,101631
# 3,Ilam,64502,290254,141126,149128
# 4,Jhapa,184552,812650,385096,427554

Upvotes: 2

Related Questions