【问题标题】:Convert NULL from Python to R using rpy2使用 rpy2 将 NULL 从 Python 转换为 R
【发布时间】:2019-09-02 08:26:01
【问题描述】:

在 R 中,NULL 值通常用作默认值。使用 Python 和 RPy2,如何显式提供 NULL 参数?

None 不可转换 (NotImplementedError),字符串 'NULL' 只会被转换为字符串并在执行过程中导致错误。

tsintermittent 包为例:

import numpy as np
from rpy2.robjects.packages import importr
from rpy2.robjects import numpy2ri

numpy2ri.activate()

tsintermittent = importr('tsintermittent')
crost = tsintermittent.crost

ts = np.random.randint(0,2,50) * np.random.randint(1,10,50)

# implicit ok, default w is NULL
# crost(ts)

# explicit - how to do it?
# RRunTimeError - non numeric argument
crost(ts, w='NULL')
# NotImplementedError
crost(ts, w=None)

【问题讨论】:

    标签: r python-3.x null rpy2


    【解决方案1】:

    您可以使用r 对象导入as.null,然后调用该函数。例如:

    from rpy2.robjects import r
    
    as_null = r['as.null']
    is_null = r['is.null']
    print(is_null(as_null())) #prints TRUE
    

    我没有尝试你的代码,因为它的所有依赖项,但如果as_null 定义如上,你应该可以使用

    crost(ts, w=as_null())
    

    或者,直接从robjects使用NULL对象定义:

    import rpy2.robjects as robj
    
    print(is_null(robj.NULL)) #prints TRUE
    

    【讨论】:

    • 谢谢,@jpcoleman,多亏了这个,我找到了我喜欢的解决方案。我已经编辑添加它。
    【解决方案2】:

    问题可能是由于NULL 中的引号引起的。无法与rpy2 核对(因为有安装问题)。下面是使用pyper的代码

    from pyper import *
    import numpy as np
    r=R(use_pandas=True)
    ts = np.random.randint(0,2,50) * np.random.randint(1,10,50)
    r('library(tsintermittent)')
    r.assign('ts1', ts)
    r('out <- crost(ts1, w = NULL)')
    out1 = r.get('out')
    out1.keys()
    #['frc.out', 'initial', 'weights', 'components', 'model', 'frc.in']
    

    无法使用rpy2 测试问题。可能是反引号是阅读它的一个选项

    crost(ts, w = `NULL`)
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 2013-08-03
      • 2014-07-31
      • 2018-01-03
      相关资源
      最近更新 更多