如何在编写R .csv文件时控制双引号

时间:2022-09-15 15:11:40

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:

我的情况是我正在尝试将包含具有不同数据类型的列的数据帧写入R中的csv文件。我用来编写该文件的代码是:

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.

当我尝试将csv文件加载到SQL数据库中时,这会导致问题,因为某些列包含包含','的字符串。如果我在上面的代码中设置quote = TRUE,那么当我加载到数据库时,它会为我的数值数据类型带来问题。

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.

我的问题:有没有办法控制R在编写csv文件时为列添加引号的方式?我希望能够在字符串周围添加引号,但不能添加其他数据类型。

Many thanks for your help.

非常感谢您的帮助。

1 个解决方案

#1


10  

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:

PS:如果你想自动计算出哪些列可以单独留下,你可以这样做:

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 )

#1


10  

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:

PS:如果你想自动计算出哪些列可以单独留下,你可以这样做:

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 )