質問

次のカンマ区切りファイルを考えます。単純さのためにそれに1行を含めることができます:


'I am quoted','so, can use comma inside - it is not separator here','but can\'t use escaped quote :=('
.

コマンドで読み込もうとしたら

table <- read.csv(filename, header=FALSE)
.

線には3つのコンマが含まれているため、線は4部分に分けられます。実際、私は3つの部分を読みたい、そのうちの1つはコンマ自体が含まれています。見積られたフラグが助けに来る。私は試しました:

table <- read.csv(filename, header=FALSE, quote="'")
.

しかし、それはエラー"incomplete final line found by readTableHeader on table"で落ちます。それは奇数(7)の引用符のために起こる。

read.table()scan()には、Parameter allowEscapesがありますが、TRUEに設定するとは役に立ちません。それは大丈夫です、help(scan)から読むことができます:

解釈されたエスケープはコントロール文字です '\ a、\ b、\ f、\ n、\ r、\ t、\ t、... ...その他のエスケープ キャラクターは、バックスラッシュを含むそれ自体として扱われます。

エスケープされた\'引用符を含むそのような引用されたCSVファイルをどのように読み取るのかをお勧めします。

役に立ちましたか?

解決

One possibility is to use readLines() to get everything read in as is, and then proceed by replacing the quote character by something else, eg :

tt <- readLines("F:/temp/test.txt")
tt <- gsub("([^\\]|^)'","\\1\"",tt) # replace ' by "
tt <- gsub("\\\\","\\",tt) # get rid of the double escape due to readLines

This allows you to read the vector tt in using a textConnection

zz <- textConnection(tt)
read.csv(zz,header=F,quote="\"") # give text input
close(zz)

Not the most beautiful solution, but it works (provided you don't have a " character somewhere in the file off course...)

他のヒント

read_delim from package readr can handle escaped quotes, using the arguments escape_double and escape_backslash.

read_delim(file, delim=',', escape_double=FALSE, escape_backslash=TRUE, quote="'")

(Note older versions of readr do not support quoted newlines in CSV headers correctly: https://github.com/tidyverse/readr/issues/784)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top