“ValueError: codes need to be between -1 and len(categories)-1” when extracting null values in rpy2










0














In using rpy2 with a built-in dataset from the synthpop R package (SD2011), I get this error:



robjects.r('head(SD2011)')
# ...
# ValueError: codes need to be between -1 and len(categories)-1


I drilled down the problem into a column which has null entries, e.g. I get the same error when doing this, but not adjacent rows or columns:



robjects.r('SD2011[3, 27]')


I confirmed this is a null value with:



robjects.r('is.na(SD2011[, 27])')
# array([0, 0, 1, ..., 0, 0, 0], dtype=int32)


Why is rpy2 not handling this gracefully?



Here's my notebook running through it.










share|improve this question


























    0














    In using rpy2 with a built-in dataset from the synthpop R package (SD2011), I get this error:



    robjects.r('head(SD2011)')
    # ...
    # ValueError: codes need to be between -1 and len(categories)-1


    I drilled down the problem into a column which has null entries, e.g. I get the same error when doing this, but not adjacent rows or columns:



    robjects.r('SD2011[3, 27]')


    I confirmed this is a null value with:



    robjects.r('is.na(SD2011[, 27])')
    # array([0, 0, 1, ..., 0, 0, 0], dtype=int32)


    Why is rpy2 not handling this gracefully?



    Here's my notebook running through it.










    share|improve this question
























      0












      0








      0







      In using rpy2 with a built-in dataset from the synthpop R package (SD2011), I get this error:



      robjects.r('head(SD2011)')
      # ...
      # ValueError: codes need to be between -1 and len(categories)-1


      I drilled down the problem into a column which has null entries, e.g. I get the same error when doing this, but not adjacent rows or columns:



      robjects.r('SD2011[3, 27]')


      I confirmed this is a null value with:



      robjects.r('is.na(SD2011[, 27])')
      # array([0, 0, 1, ..., 0, 0, 0], dtype=int32)


      Why is rpy2 not handling this gracefully?



      Here's my notebook running through it.










      share|improve this question













      In using rpy2 with a built-in dataset from the synthpop R package (SD2011), I get this error:



      robjects.r('head(SD2011)')
      # ...
      # ValueError: codes need to be between -1 and len(categories)-1


      I drilled down the problem into a column which has null entries, e.g. I get the same error when doing this, but not adjacent rows or columns:



      robjects.r('SD2011[3, 27]')


      I confirmed this is a null value with:



      robjects.r('is.na(SD2011[, 27])')
      # array([0, 0, 1, ..., 0, 0, 0], dtype=int32)


      Why is rpy2 not handling this gracefully?



      Here's my notebook running through it.







      python r rpy2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 6:27









      Max Ghenis

      4,54963158




      4,54963158






















          1 Answer
          1






          active

          oldest

          votes


















          1















          Why is rpy2 not handling this gracefully?




          This seems like a bug triggered during the conversion of the R factor to pandas with rpy2 versions 2.9.x (the dev branch default, future 3.0.x, does not have this issue). Specifically when doing:



          res = pandas.Categorical.from_codes(numpy.asarray(obj) - 1,
          categories = obj.do_slot('levels'),
          ordered = 'ordered' in obj.rclass)


          R "factor" objects are vector of integers, with each integer an index in an associated vector of "levels". The converter is simply subtracting one because R arrays are one-indexed and Python arrays are zero-index, but this is breaking whenever there are missing values (NAs) because R is using a specific integer to encode missing integers (an extreme value) and Python, numpy, and pandas does not have an equivalence for this.



          I opened an issue to track this and in the meantime, workarounds can be to replace the NAs on the R side to a level (and call them, say, "missing" or "NA"), change the factors to arrays of strings, or to modify the pandas converter for R factors. For example:



          robjects.r("""
          SD2011_nofactor <- SD2011 %>%
          dplyr::mutate_if(is.factor,
          funs(as.character(.))
          """)


          (Or use rpy2's Pythonic interface to dplyr)



          Note:



          Few things are succcessively happening when doing:



          robjects.r('SD2011[3, 27]')


          1. the R code SD2011[3, 27] is evaluated

          2. the result of that evaluation is going through the robjects-level conversion

          3. the object resulting from that conversion is shown in your notebook

          If unsure, finding which one of the Python statements below is the first to fail can tell it:




          1. Evaluate the R code (the added TRUE is to prevent the evaluation from returning
            x).



            robjects.r('x <- SD2011[3, 27]; TRUE')



          2. Fetch the object x obtained from the evaluation above and bind it to a Python symbol (the conversion will be aplied).



            x = robjects.r('x')



          3. Show a text representation of the converted object



            repr(x)






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236532%2fvalueerror-codes-need-to-be-between-1-and-lencategories-1-when-extracting%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1















            Why is rpy2 not handling this gracefully?




            This seems like a bug triggered during the conversion of the R factor to pandas with rpy2 versions 2.9.x (the dev branch default, future 3.0.x, does not have this issue). Specifically when doing:



            res = pandas.Categorical.from_codes(numpy.asarray(obj) - 1,
            categories = obj.do_slot('levels'),
            ordered = 'ordered' in obj.rclass)


            R "factor" objects are vector of integers, with each integer an index in an associated vector of "levels". The converter is simply subtracting one because R arrays are one-indexed and Python arrays are zero-index, but this is breaking whenever there are missing values (NAs) because R is using a specific integer to encode missing integers (an extreme value) and Python, numpy, and pandas does not have an equivalence for this.



            I opened an issue to track this and in the meantime, workarounds can be to replace the NAs on the R side to a level (and call them, say, "missing" or "NA"), change the factors to arrays of strings, or to modify the pandas converter for R factors. For example:



            robjects.r("""
            SD2011_nofactor <- SD2011 %>%
            dplyr::mutate_if(is.factor,
            funs(as.character(.))
            """)


            (Or use rpy2's Pythonic interface to dplyr)



            Note:



            Few things are succcessively happening when doing:



            robjects.r('SD2011[3, 27]')


            1. the R code SD2011[3, 27] is evaluated

            2. the result of that evaluation is going through the robjects-level conversion

            3. the object resulting from that conversion is shown in your notebook

            If unsure, finding which one of the Python statements below is the first to fail can tell it:




            1. Evaluate the R code (the added TRUE is to prevent the evaluation from returning
              x).



              robjects.r('x <- SD2011[3, 27]; TRUE')



            2. Fetch the object x obtained from the evaluation above and bind it to a Python symbol (the conversion will be aplied).



              x = robjects.r('x')



            3. Show a text representation of the converted object



              repr(x)






            share|improve this answer



























              1















              Why is rpy2 not handling this gracefully?




              This seems like a bug triggered during the conversion of the R factor to pandas with rpy2 versions 2.9.x (the dev branch default, future 3.0.x, does not have this issue). Specifically when doing:



              res = pandas.Categorical.from_codes(numpy.asarray(obj) - 1,
              categories = obj.do_slot('levels'),
              ordered = 'ordered' in obj.rclass)


              R "factor" objects are vector of integers, with each integer an index in an associated vector of "levels". The converter is simply subtracting one because R arrays are one-indexed and Python arrays are zero-index, but this is breaking whenever there are missing values (NAs) because R is using a specific integer to encode missing integers (an extreme value) and Python, numpy, and pandas does not have an equivalence for this.



              I opened an issue to track this and in the meantime, workarounds can be to replace the NAs on the R side to a level (and call them, say, "missing" or "NA"), change the factors to arrays of strings, or to modify the pandas converter for R factors. For example:



              robjects.r("""
              SD2011_nofactor <- SD2011 %>%
              dplyr::mutate_if(is.factor,
              funs(as.character(.))
              """)


              (Or use rpy2's Pythonic interface to dplyr)



              Note:



              Few things are succcessively happening when doing:



              robjects.r('SD2011[3, 27]')


              1. the R code SD2011[3, 27] is evaluated

              2. the result of that evaluation is going through the robjects-level conversion

              3. the object resulting from that conversion is shown in your notebook

              If unsure, finding which one of the Python statements below is the first to fail can tell it:




              1. Evaluate the R code (the added TRUE is to prevent the evaluation from returning
                x).



                robjects.r('x <- SD2011[3, 27]; TRUE')



              2. Fetch the object x obtained from the evaluation above and bind it to a Python symbol (the conversion will be aplied).



                x = robjects.r('x')



              3. Show a text representation of the converted object



                repr(x)






              share|improve this answer

























                1












                1








                1







                Why is rpy2 not handling this gracefully?




                This seems like a bug triggered during the conversion of the R factor to pandas with rpy2 versions 2.9.x (the dev branch default, future 3.0.x, does not have this issue). Specifically when doing:



                res = pandas.Categorical.from_codes(numpy.asarray(obj) - 1,
                categories = obj.do_slot('levels'),
                ordered = 'ordered' in obj.rclass)


                R "factor" objects are vector of integers, with each integer an index in an associated vector of "levels". The converter is simply subtracting one because R arrays are one-indexed and Python arrays are zero-index, but this is breaking whenever there are missing values (NAs) because R is using a specific integer to encode missing integers (an extreme value) and Python, numpy, and pandas does not have an equivalence for this.



                I opened an issue to track this and in the meantime, workarounds can be to replace the NAs on the R side to a level (and call them, say, "missing" or "NA"), change the factors to arrays of strings, or to modify the pandas converter for R factors. For example:



                robjects.r("""
                SD2011_nofactor <- SD2011 %>%
                dplyr::mutate_if(is.factor,
                funs(as.character(.))
                """)


                (Or use rpy2's Pythonic interface to dplyr)



                Note:



                Few things are succcessively happening when doing:



                robjects.r('SD2011[3, 27]')


                1. the R code SD2011[3, 27] is evaluated

                2. the result of that evaluation is going through the robjects-level conversion

                3. the object resulting from that conversion is shown in your notebook

                If unsure, finding which one of the Python statements below is the first to fail can tell it:




                1. Evaluate the R code (the added TRUE is to prevent the evaluation from returning
                  x).



                  robjects.r('x <- SD2011[3, 27]; TRUE')



                2. Fetch the object x obtained from the evaluation above and bind it to a Python symbol (the conversion will be aplied).



                  x = robjects.r('x')



                3. Show a text representation of the converted object



                  repr(x)






                share|improve this answer















                Why is rpy2 not handling this gracefully?




                This seems like a bug triggered during the conversion of the R factor to pandas with rpy2 versions 2.9.x (the dev branch default, future 3.0.x, does not have this issue). Specifically when doing:



                res = pandas.Categorical.from_codes(numpy.asarray(obj) - 1,
                categories = obj.do_slot('levels'),
                ordered = 'ordered' in obj.rclass)


                R "factor" objects are vector of integers, with each integer an index in an associated vector of "levels". The converter is simply subtracting one because R arrays are one-indexed and Python arrays are zero-index, but this is breaking whenever there are missing values (NAs) because R is using a specific integer to encode missing integers (an extreme value) and Python, numpy, and pandas does not have an equivalence for this.



                I opened an issue to track this and in the meantime, workarounds can be to replace the NAs on the R side to a level (and call them, say, "missing" or "NA"), change the factors to arrays of strings, or to modify the pandas converter for R factors. For example:



                robjects.r("""
                SD2011_nofactor <- SD2011 %>%
                dplyr::mutate_if(is.factor,
                funs(as.character(.))
                """)


                (Or use rpy2's Pythonic interface to dplyr)



                Note:



                Few things are succcessively happening when doing:



                robjects.r('SD2011[3, 27]')


                1. the R code SD2011[3, 27] is evaluated

                2. the result of that evaluation is going through the robjects-level conversion

                3. the object resulting from that conversion is shown in your notebook

                If unsure, finding which one of the Python statements below is the first to fail can tell it:




                1. Evaluate the R code (the added TRUE is to prevent the evaluation from returning
                  x).



                  robjects.r('x <- SD2011[3, 27]; TRUE')



                2. Fetch the object x obtained from the evaluation above and bind it to a Python symbol (the conversion will be aplied).



                  x = robjects.r('x')



                3. Show a text representation of the converted object



                  repr(x)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 18 at 3:24

























                answered Nov 10 at 18:57









                lgautier

                8,7431836




                8,7431836



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236532%2fvalueerror-codes-need-to-be-between-1-and-lencategories-1-when-extracting%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                    Edmonton

                    Crossroads (UK TV series)