2013-08-02 14 views
14

私は、彼らがRに振る舞うようブールNA値を複製する:欠損値のブール代数を行う方法は?

NAが有効な論理オブジェクトです。 xまたはyの成分がNAである場合、結果があいまいである場合、結果はNAになります。言い換えれば、NA & TRUEはNAと評価されますが、NA & FALSEはFALSEと評価されます。私はNoneを見てきました http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html

は、欠損値のために推奨されているが、Pythonはブール式を評価するときにFalseNoneを変換し、FalseからNone or Falseを計算します。その結果は、当然のことながら、Noneとなっているはずですが、欠落値を理由に結論を出すことはできません。

これをPythonでどのように達成できますか?

EDIT受け入れ答えは、ビット単位の論理演算子を正しく計算しますが、論理演算子notorandと同じ動作を実現するために、Pythonプログラミング言語の変更を必要とするようです。

+0

'(ラムダX:X |〜X)(NA)'? – SingleNegationElimination

答えて

9

他にも、独自のクラスを定義することができます。

class NA_(object): 
    instance = None # Singleton (so `val is NA` will work) 
    def __new__(self): 
     if NA_.instance is None: 
      NA_.instance = super(NA_, self).__new__(self) 
     return NA_.instance 
    def __str__(self): return "NA" 
    def __repr__(self): return "NA_()" 
    def __and__(self, other): 
     if self is other or other: 
      return self 
     else: 
      return other 
    __rand__ = __and__ 
    def __or__(self, other): 
     if self is other or other: 
      return other 
     else: 
      return self 
    __ror__ = __or__ 
    def __xor__(self, other): 
     return self 
    __rxor__ = __xor__ 
    def __eq__(self, other): 
     return self is other 
    __req__ = __eq__ 
    def __nonzero__(self): 
     raise TypeError("bool(NA) is undefined.") 
NA = NA_() 

用途:

>>> print NA & NA 
NA 
>>> print NA & True 
NA 
>>> print NA & False 
False 
>>> print NA | True 
True 
>>> print NA | False 
NA 
>>> print NA | NA 
NA 
>>> print NA^True 
NA 
>>> print NA^NA 
NA 
>>> if NA: print 3 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 28, in __nonzero__ 
TypeError: bool(NA) is undefined. 
>>> if NA & False: print 3 
... 
>>> 
>>> if NA | True: print 3 
... 
3 
>>> 
+1

あなたの答えは気に入っていますが、あなたはまだNAまたはTrueをTrueに評価することができませんか?あなたの例では、ビット演算子を使用しています。 – user2646234

+1

私が知る限り、 "or"と "and"をオーバーライドすることは不可能です。 'NAまたはTrue'は'(NA .__ nonzero __()== True)と解釈されます。 (True .__非ゼロ__()==真) '。私が間違っているなら、私を修正してください。私はこれについて間違っているのが大好きです。 http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types –

6

:これを参照してください。

>>> class NA_type(object): 
     def __and__(self,other): 
       if other == True: 
         return self 
       else: 
         return False 
     def __str__(self): 
       return 'NA' 


>>> 
>>> NA = NA_type() 
>>> print NA & True 
NA 
>>> print NA & False 
False 
+2

「NA&NA」はFalseを返します。おそらく望ましい動作ではないでしょう。また、 'NA:do_whatever()'が 'do_whatever()'を警告なしでも実行するという事実について何かするのは良いことかもしれません。 – user2357112

+0

@ user2357112私は答えの2つの点に答えました –

+0

@Chris Barkerはい、あなたの答えははるかに完全です。私はちょうど飛び降りる点を与えていた。 – Brien

関連する問題