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.
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.
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.
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.
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With