如何有条件地删除write.csv中的引号? [英] How to conditionally remove quotes in write.csv?

查看:93
本文介绍了如何有条件地删除write.csv中的引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用write.csv时,可以通过使用quote=FALSE删除引号来显着减小文件大小(对于大型数据集,大约减小25%).但是,如果您的数据中包含逗号,这可能会导致read.csv出现故障.例如:

When using write.csv, one may reduce file sizes significantly (approx 25% for large datasets) by removing quotes using quote=FALSE. However, this may cause read.csv to malfunction if commas are present in your data. For example:

x <- data.frame(a=1:2,b=c("hello,","world"))
dim(x)
[1] 2 2
f <- tempfile()
write.csv(x,f,row.names=FALSE,quote=FALSE)
dim(read.csv(f))
[1] 2 2
read.csv(f)
      a  b
1 hello NA
2 world NA

观察列名未对齐,数据丢失和伪造数据的添加.

Observe column name misalignment and a loss of data and addition of spurious data.

是否可以通常删除引号,但是对于数据中包含逗号的字段,可以保留引号?

Is is possible to remove quotes generally, but maintain them for fields that have commas in the data?

推荐答案

我采用的解决方案是@TimPietzcker和@BenBolker的评论的组合.

The solution I went with was a combination of the comments of @TimPietzcker and @BenBolker.

quote可以是一个数字向量,用于指定要引用哪些列.尽管我希望只在需要时才引用,但在我看来,这几乎可以减少文件的全部大小(也使用na="").

quote can be a numeric vector to specify which columns get quoted. While I would have preferred to only quote when needed, this allowed almost the full file-size reduction in my case (also using na="").

commas <- which(sapply(x, function(y) any(grepl(",",y))))
write.csv(x,f,row.names=FALSE,quote=commas)
read.csv(f)
  a      b
1 1 hello,
2 2  world

这篇关于如何有条件地删除write.csv中的引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆