LoginSignup
18

More than 5 years have passed since last update.

RのUTF-8で漢字などが入っている場合read.tableができない

Last updated at Posted at 2015-10-09

この記事を書くことになった原因。
そもそもなんでread.tableが使えないの、ということに対する記事。

CSVファイルがUTF-8のため起こった問題。
read.tableのエンコード指定にUTF-8を行っているのに、区切り文字が認識されずエラーがでる。

前提条件:「C:\hoge\piyo.csv」のファイルを読み込むとする。エンコードはUTF-8。使用機はWindows 7 32bit。

piyo.csv
test1,test2,test3
1,普通,2
3,簡単,4
エラー内容
> d <- read.table("C:\\hoge\\piyo.csv", sep=",", skip=0, header=T, stringsAsFactors=F, encoding="UTF-8")
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 1 did not have 3 elements
> 

エンコード指定しているのにUTF-8で読みこめてない・・?
ユニコード.png
たぶんこんな感じで読みこんでいるイメージ

UTF-8で読み込めていないので、どうやら区切り文字がくっついている模様。
これでいろいろ行ってみましたが解決できなかったので、read.tableしない選択を選びました。
もし原因分かる方いたらよろしくお願いします。


追記:さっくり解決してしまった。コメントありがとうございます。

 d <- read.table("C:\\hoge\\piyo.csv", sep=",", skip=0, header=T, stringsAsFactors=F, encoding="UTF-8")

このencoding="UTF-8"の部分が間違っていたようで、fileEncoding="UTF-8"とするだけ!
encodingは読み込んだ後の文字コードの指定らしいです。なるほど・・。

 d <- read.table("C:\\hoge\\piyo.csv", sep=",", skip=0, header=T, stringsAsFactors=F, fileEncoding="UTF-8")

※fileEncodingの「E」は大文字なので注意!


Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18