How to use the lambda argument of smooth.spline in RPy WITHOUT Python interprating it as lambda

后端 未结 3 1949
臣服心动
臣服心动 2020-12-19 17:36

I want to use the natural cubic smoothing splines smooth.spline from R in Python (like som many others want as well (Python natural smoothing splines, Is there

相关标签:
3条回答
  • 2020-12-19 18:28

    Perhaps you could use rpy2's Function.rcall() method when calling smooth.spline?

    import rpy2.robjects as robjects
    r_y = robjects.FloatVector(y_train)
    r_x = robjects.FloatVector(x_train)
    
    r_smooth_spline = robjects.r['smooth.spline']
    args = (('x',r_x), ('y',r_y), ('lambda',42)) # pattern (('argname', value),...)
    
    # import R's "GlobalEnv" to evaluate the function
    from rpy2.robjects import globalenv
    
    spline1 = r_smooth_spline.rcall(args, globalenv)
    
    0 讨论(0)
  • 2020-12-19 18:39

    This little trick will work around the specific problem you're having, by allowing you to write "lambda" in a string.

    kwargs = {"x": r_x, "y": r_y, "lambda":  42}
    spline1 = r_smooth_spline(**kwargs)
    

    In the general case, you can pass around argument containers easily with tuples and dicts.

    # as normal
    f = function("foo", "bar", my_kwarg="my_value")
    
    # the same call using argument containers
    args = ("foo", "bar")
    kwargs = {"my_kwarg": "my_value"}
    f = function(*args, **kwargs)
    
    0 讨论(0)
  • 2020-12-19 18:40

    You can use Python's **<dict> in a function call to specify R named arguments that have a name that is not syntactically valid in Python.

    See the documentation for more details: https://rpy2.github.io/doc/v3.2.x/html/robjects_functions.html

    0 讨论(0)
提交回复
热议问题