StatsBeginner: 初学者の統計学習ノート

統計学およびR、Pythonでのプログラミングの勉強の過程をメモっていくノート。たまにMacの話題。

Rの練習: fisher.test()でメモリが足りなくなる

 ちょっとしたデータをカイ二乗検定しようとすると、往々にして、期待度数が5に満たないセルが存在するせいで警告が出ます。

> print(d)
       Group.1 Group.2
Item.1       3       2
Item.2       9      12
Item.3      32      41
Item.4      68      74
Item.5      90      91
Item.6      35      32
Item.7      17       4
> chisq.test(d)

	Pearson's Chi-squared test

data:  d
X-squared = 10.1715, df = 6, p-value = 0.1176

Warning message:
In chisq.test(d) : Chi-squared approximation may be incorrect
> 


 こういう場合はフィッシャーの正確確率検定を行うわけですが、

> fisher.test(d, alternative = "two.sided")
Error in fisher.test(d, alternative = "two.sided") : FEXACT error 7.
LDSTP is too small for this problem.
Try increasing the size of the workspace.
> 


 というエラーが出てしまいました。
 調べると、

You can try increasing the workspace argument from its default value, but I don't know if you're going to be able to make it big enough (I gave up at workspace=2e8, which still fails; I ran out of memory at workspace=2e9.) You can also try simulated p-values, e.g. fisher.test(Finaltable,simulate.p.value=TRUE,B=1e7) (for example), but since the p-value is extremely small, you're going to need a huge number of simulations (B) if you want to do more than bound the p-value, which will also be very slow. (For most purposes, knowing that p is <1e-7 is more than enough -- but in some bioinformatics contexts people want to use p as an index of signal strength and/or impose massive multiple-corrections comparisons. I don't really like these approaches, but they're out there ...)
 
r - Fisher test error : LDSTP is too small - Stack Overflow


 というアドバイスがありました。メモリの割り当て?を増やせばいいらしい。そういう引数があるのか。
 よくわからんかったのでほかのページをみると、

workspace
2x2より大きい分割表を対象とする場合に、正確なp値を計算するためのメモリ容量を指定。整数を指定。
 
simulate.p.value
2x2より大きい分割表を対象とする場合に、p値の算出にモンテカルロシミュレーションを用いるかどうかの指定。'T' または 'F' で指定。
 
Rによるフィッシャーの直接確率検定


 と書いてあった。フィッシャーの正確確率検定は、Wikipediaに書いてるように計算のなかに階乗が登場することと、このページで計算されているように合計値を固定して全通りを洗い出すという方法なので、計算にけっこうリソースがいるらしい。たしかに2x2じゃない場合パターンいっぱいになりますね。


 今回の私のデータの場合、workspace=1000000ぐらいまで大きくすると計算できました。

> fisher.test(d, alternative = "two.sided", workspace=1000000)

Fisher's Exact Test for Count Data

data: d
p-value = 0.1023
alternative hypothesis: two.sided


 for文のなかで7回ぐらいいっぺんにやろうとすると、workspace=100000000(1億)にしないとダメでしたが。