R:仅在文本上使用双引号导入CSV

时间:2015-06-02 19:20:37

标签: r import double-quotes

我正在尝试导入CSV,其中文本列是双引号但数字列不是。我总共有95列,所以我无法手动修改列。 (注意:文中有逗号我无法删除)

下面是一个示例数据集来说明我的问题。

CSV文件:

select * from table where
q_date >= date '2009-03-16'
and q_date < date '2009-03-17';

期望的输出:

"Column 1","Column 2","Column 3","Column 4","Column 5"

2,"A,A","B,Z","C,C",44

3,"A,X","B,B","C,C",121

我试过了:

Column 1    Column 2  Column3   Column4 Column5
   2          A,A      B,Z        C,C       44
   3          A,X      B,B        C,C      121

2 个答案:

答案 0 :(得分:1)

tf <- tempfile()
csv <- '"Column 1","Column 2","Column 3","Column 4","Column 5"\n\n2,"A,A","B,Z","C,C",44\n\n3,"A,X","B,B","C,C",121'
writeLines( csv , tf )
x <- read.csv( tf )

      Column.1 Column.2 Column.3 Column.4 Column.5
1        2      A,A      B,Z      C,C       44
2        3      A,X      B,B      C,C      121

答案 1 :(得分:0)

删除空行,因为read.table无法接受

readLines(textConnection(txt)) -> rl  # readLines('csvfile.csv') for you
rl[1:length(rl) %% 2 == 1] -> rl2
read.table(text = rl2, sep = ',', h = TRUE)

<强>输出:

  Column.1 Column.2 Column.3 Column.4 Column.5
1        2      A,A      B,Z      C,C       44
2        3      A,X      B,B      C,C      121

数据:

txt <- '"Column 1","Column 2","Column 3","Column 4","Column 5"

2,"A,A","B,Z","C,C",44

3,"A,X","B,B","C,C",121'