Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control double quotes when writing R .csv files

Tags:

r

csv

My situation is that I am attempting to write a data frame consisting of columns that have differing data types to a csv file in R. The code I use to write the file is:

filename = file("equipment.csv")
write.csv(file = filename, x = equipment, quote = FALSE, row.names = FALSE ) 

This causes problems later when I try to load the csv file into a SQL database since some of the columns contain strings that contain ','. If I set quote = TRUE in the above code, it creates problems for my numeric data types when I load to the data base.

My question: is there a way to control the way that R adds quotes to the columns when writing csv files? I would like to be able to add quotes around the strings but not to the other data types.

Many thanks for your help.

like image 898
Sledge Avatar asked Nov 26 '13 13:11

Sledge


People also ask

How do you handle double quotes in CSV?

Yes. You can import double quotation marks using CSV files and import maps by escaping the double quotation marks. To escape the double quotation marks, enclose them within another double quotation mark.

Why does my CSV have double quotes?

CSV files use double-quote marks to delimit field values that have spaces, so a value like Santa Claus gets saved as “Santa Claus” to preserve the space. If a field value contains double-quotes, then the double-quotes get doubled-up so the parser can tell the difference.

How do I replace a double quote in a CSV file?

If you want to remove all double quotes, simply select the entire worksheet, then go to the Editing group of the Home tab and click the Find and select drop down. Click on Replace (or hit CTRL + h). In the “Find what” field of the Dialog box type in a double quote.

How do I remove quote marks from data in R?

Sometimes column values in an R data frame have single quote associated with them and to perform the analysis we need to remove that quote. Therefore, to remove single quote from string column, we can use gsub function by defining the single quote and replacing it with blank(not space) as shown in the below examples.


1 Answers

Specify which columns you want quoted like this

write.csv(file = filename, x = equipment, quote = c(2,3), row.names = FALSE )

PS: if you want to automatically work out which columns to leave alone, you can do it like this:

non_numerics<-adply(1:ncol(equipment),1,function(x)print(is.numeric(equipment[,x])))
quote_val<-as.numeric(array(non_numerics[which(!non_numerics$V1),1]))

filename = file("equipment.csv")
write.csv(file = filename, x = equipment, quote = quote_val, row.names = FALSE )
like image 85
Troy Avatar answered Sep 19 '22 05:09

Troy