简体   繁体   中英

R: Import CSV with double quotes only on text

I am trying to import a CSV where the text columns are in double quotes but the numeric columns are not. I have 95 columns in total so I cannot manually modify the columns. (Note: There are commas in the text that I cannot remove)

Below is a sample data set to illustrate my problem.

CSV File:

"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

Desired Output:

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

I tried:

       test=read.csv('test.csv', header=TRUE,sep =",")
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

Remove blank lines as read.table can't accept them

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

Output:

  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

Data:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM