0

I have a python dictionary with values defined as follows:

dc = {
    '1': 100,
    '2': 150,
    '3': 200
  }

And a r function defined as follows:

Printer <- function(...) {
    for (i in list(...)) {
        print (i)
    }
}

So the output would be

 100
 150
 200

The error I get when trying to pass the argument through rpy2 is

RuntimeError: Unknown data type <class 'dict'> to pass to R algorithm.

Question: How do I convert the elements of the python dictionary to an r list during passing from python to R?

Heikki
  • 2,214
  • 19
  • 34
FlyingPickle
  • 1,047
  • 1
  • 9
  • 19
  • Alternately Can I pass a dict argument to R and perhaps convert it to a list in the R function (just thinking out aloud of my options here). – FlyingPickle Aug 20 '20 at 18:54
  • Does this answer your question? [How can I get list of values from dict?](https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict) – mkrieger1 Aug 20 '20 at 18:55

1 Answers1

1

For a simple use case and a flat dict this snippet can be utilized.

import rpy2.robjects as robjects
a = robjects.r('list(foo="barbat", fizz=123)')

Here is a snippet for conversion:

def _dict_to_rlist(dd):
    pairs = []
    for k,v in dd.items():
        if isinstance(v, str):
            pairs.append("{}=\"{}\"".format(k, v))
        else:
            pairs.append("{}={}".format(k, v))
    cmd = "list({})".format(",".join(pairs))
    lst = ro.r(cmd)
    return lst