Reputation: 1345
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.
Upvotes: 16
Views: 21211
Reputation: 8691
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 )
Upvotes: 15