0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【R】readrでの固定長データ読み込みでデータが抜け落ちる

Last updated at Posted at 2020-12-06

固定長データの読み込みについて過去の記事で紹介しました。例えば、固定長データの1行目とn行目が以下のようだとします。

1行目:aaabbccc
  $\vdots$
n行目:aaabbcccdd

すなわち、最初の3文字が変数a、次の2文字が変数b、続き3文字が変数cという具合です。このとき、radrパッケージを使って読み込むとすれば

readr_fwd.rb
d <- read_fwf(datafilename.txt, fwf_widths(c(3, 2, 3, 2), col_names = c("a", "b", "c", "d")))

となるわけです。

例えば、変数dが、1~(n-1)行目までは現れず、n行目で初めて現れるとします。そうしたときに、nが1,000よりも大きいとき、readrパッケージでは(デフォルトで)最初の1,000行を使ってデータ形式を予測(guess)するため、変数dがうまく読み込めず、抜け落ちてしまうことがわかりました。

こんなエラーが出ます

Warning: *** parsing failures.
row      col    expected actual         file
1000     d      1/0/T/F/TRUE/FALSE      3 'datafilename.txt'

この問題を回避するために、read_fwfのオプションで、guess_maxを指定してやると、うまくいくことがわかりました。たとえば、guess_maxを10,000とかにしてやるとうまくいきます。

readr_fwd_guess_max.rb
d <- read_fwf(datafilename.txt, fwf_widths(c(3, 2, 3, 2), col_names = c("a", "b", "c", "d")), , guess_max = 10000 ) 
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?