Calculate row-wise proportions











up vote
14
down vote

favorite
3












I have a data frame:



x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
# id val0 val1 val2
# 1 a 1 4 7
# 2 b 2 5 8
# 3 c 3 6 9


Within each row, I want to calculate the corresponding proportions (ratio) for each value. E.g. for the value in column "val0", I want to calculate row-wise val0 / (val0 + val1 + val2).



Desired output:



  id     val0  val1   val2
1 a 0.083 0.33 0.583
2 b 0.133 0.33 0.533
3 c 0.167 0.33 0.5


Can anyone tell me what's the best way to do this? Here it's just three columns, but there can be alot of columns.










share|improve this question




























    up vote
    14
    down vote

    favorite
    3












    I have a data frame:



    x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
    # id val0 val1 val2
    # 1 a 1 4 7
    # 2 b 2 5 8
    # 3 c 3 6 9


    Within each row, I want to calculate the corresponding proportions (ratio) for each value. E.g. for the value in column "val0", I want to calculate row-wise val0 / (val0 + val1 + val2).



    Desired output:



      id     val0  val1   val2
    1 a 0.083 0.33 0.583
    2 b 0.133 0.33 0.533
    3 c 0.167 0.33 0.5


    Can anyone tell me what's the best way to do this? Here it's just three columns, but there can be alot of columns.










    share|improve this question


























      up vote
      14
      down vote

      favorite
      3









      up vote
      14
      down vote

      favorite
      3






      3





      I have a data frame:



      x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
      # id val0 val1 val2
      # 1 a 1 4 7
      # 2 b 2 5 8
      # 3 c 3 6 9


      Within each row, I want to calculate the corresponding proportions (ratio) for each value. E.g. for the value in column "val0", I want to calculate row-wise val0 / (val0 + val1 + val2).



      Desired output:



        id     val0  val1   val2
      1 a 0.083 0.33 0.583
      2 b 0.133 0.33 0.533
      3 c 0.167 0.33 0.5


      Can anyone tell me what's the best way to do this? Here it's just three columns, but there can be alot of columns.










      share|improve this question















      I have a data frame:



      x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
      # id val0 val1 val2
      # 1 a 1 4 7
      # 2 b 2 5 8
      # 3 c 3 6 9


      Within each row, I want to calculate the corresponding proportions (ratio) for each value. E.g. for the value in column "val0", I want to calculate row-wise val0 / (val0 + val1 + val2).



      Desired output:



        id     val0  val1   val2
      1 a 0.083 0.33 0.583
      2 b 0.133 0.33 0.533
      3 c 0.167 0.33 0.5


      Can anyone tell me what's the best way to do this? Here it's just three columns, but there can be alot of columns.







      r dataframe apply






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 24 '16 at 8:22









      Henrik

      40.5k991107




      40.5k991107










      asked Apr 16 '13 at 9:02









      Rachit Agrawal

      1,42951944




      1,42951944
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          8
          down vote



          accepted










          And another alternative (though this is mostly a pretty version of sweep)... prop.table:



          > cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
          id val0 val1 val2
          1 a 0.08333333 0.3333333 0.5833333
          2 b 0.13333333 0.3333333 0.5333333
          3 c 0.16666667 0.3333333 0.5000000


          From the "description" section of the help file at ?prop.table:




          This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).




          So, you can see that underneath, this is really quite similar to @Jilber's solution.



          And... it's nice for the R developers to be considerate of us newbies, isn't it? :)






          share|improve this answer



















          • 1




            @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
            – A5C1D2H2I1M1N2O1R2T1
            Apr 16 '13 at 11:00


















          up vote
          10
          down vote













          following should do the trick



          cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
          ## id val0 val1 val2
          ## 1 a 0.08333333 0.3333333 0.5833333
          ## 2 b 0.13333333 0.3333333 0.5333333
          ## 3 c 0.16666667 0.3333333 0.5000000





          share|improve this answer





















          • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
            – Jaap
            Nov 22 at 9:47




















          up vote
          6
          down vote













          Another alternative using sweep



          sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
          val0 val1 val2
          1 0.08333333 0.3333333 0.5833333
          2 0.13333333 0.3333333 0.5333333
          3 0.16666667 0.3333333 0.5000000





          share|improve this answer




























            up vote
            4
            down vote













            The function adorn_percentages() from the janitor package does this:



            library(janitor)
            x %>% adorn_percentages()
            id val0 val1 val2
            a 0.08333333 0.3333333 0.5833333
            b 0.13333333 0.3333333 0.5333333
            c 0.16666667 0.3333333 0.5000000


            This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.



            Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.






            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',
              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%2f16032826%2fcalculate-row-wise-proportions%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              8
              down vote



              accepted










              And another alternative (though this is mostly a pretty version of sweep)... prop.table:



              > cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
              id val0 val1 val2
              1 a 0.08333333 0.3333333 0.5833333
              2 b 0.13333333 0.3333333 0.5333333
              3 c 0.16666667 0.3333333 0.5000000


              From the "description" section of the help file at ?prop.table:




              This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).




              So, you can see that underneath, this is really quite similar to @Jilber's solution.



              And... it's nice for the R developers to be considerate of us newbies, isn't it? :)






              share|improve this answer



















              • 1




                @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
                – A5C1D2H2I1M1N2O1R2T1
                Apr 16 '13 at 11:00















              up vote
              8
              down vote



              accepted










              And another alternative (though this is mostly a pretty version of sweep)... prop.table:



              > cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
              id val0 val1 val2
              1 a 0.08333333 0.3333333 0.5833333
              2 b 0.13333333 0.3333333 0.5333333
              3 c 0.16666667 0.3333333 0.5000000


              From the "description" section of the help file at ?prop.table:




              This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).




              So, you can see that underneath, this is really quite similar to @Jilber's solution.



              And... it's nice for the R developers to be considerate of us newbies, isn't it? :)






              share|improve this answer



















              • 1




                @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
                – A5C1D2H2I1M1N2O1R2T1
                Apr 16 '13 at 11:00













              up vote
              8
              down vote



              accepted







              up vote
              8
              down vote



              accepted






              And another alternative (though this is mostly a pretty version of sweep)... prop.table:



              > cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
              id val0 val1 val2
              1 a 0.08333333 0.3333333 0.5833333
              2 b 0.13333333 0.3333333 0.5333333
              3 c 0.16666667 0.3333333 0.5000000


              From the "description" section of the help file at ?prop.table:




              This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).




              So, you can see that underneath, this is really quite similar to @Jilber's solution.



              And... it's nice for the R developers to be considerate of us newbies, isn't it? :)






              share|improve this answer














              And another alternative (though this is mostly a pretty version of sweep)... prop.table:



              > cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
              id val0 val1 val2
              1 a 0.08333333 0.3333333 0.5833333
              2 b 0.13333333 0.3333333 0.5333333
              3 c 0.16666667 0.3333333 0.5000000


              From the "description" section of the help file at ?prop.table:




              This is really sweep(x, margin, margin.table(x, margin), "/") for newbies, except that if margin has length zero, then one gets x/sum(x).




              So, you can see that underneath, this is really quite similar to @Jilber's solution.



              And... it's nice for the R developers to be considerate of us newbies, isn't it? :)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 16 '13 at 10:59

























              answered Apr 16 '13 at 10:16









              A5C1D2H2I1M1N2O1R2T1

              151k18282373




              151k18282373








              • 1




                @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
                – A5C1D2H2I1M1N2O1R2T1
                Apr 16 '13 at 11:00














              • 1




                @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
                – A5C1D2H2I1M1N2O1R2T1
                Apr 16 '13 at 11:00








              1




              1




              @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
              – A5C1D2H2I1M1N2O1R2T1
              Apr 16 '13 at 11:00




              @Jilber, Thanks. Actually, it was inspired by your solution since I always remember the description of prop.table starting with saying that it is sweep for newbies (which I am, perpetually).
              – A5C1D2H2I1M1N2O1R2T1
              Apr 16 '13 at 11:00












              up vote
              10
              down vote













              following should do the trick



              cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
              ## id val0 val1 val2
              ## 1 a 0.08333333 0.3333333 0.5833333
              ## 2 b 0.13333333 0.3333333 0.5333333
              ## 3 c 0.16666667 0.3333333 0.5000000





              share|improve this answer





















              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
                – Jaap
                Nov 22 at 9:47

















              up vote
              10
              down vote













              following should do the trick



              cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
              ## id val0 val1 val2
              ## 1 a 0.08333333 0.3333333 0.5833333
              ## 2 b 0.13333333 0.3333333 0.5333333
              ## 3 c 0.16666667 0.3333333 0.5000000





              share|improve this answer





















              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
                – Jaap
                Nov 22 at 9:47















              up vote
              10
              down vote










              up vote
              10
              down vote









              following should do the trick



              cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
              ## id val0 val1 val2
              ## 1 a 0.08333333 0.3333333 0.5833333
              ## 2 b 0.13333333 0.3333333 0.5333333
              ## 3 c 0.16666667 0.3333333 0.5000000





              share|improve this answer












              following should do the trick



              cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
              ## id val0 val1 val2
              ## 1 a 0.08333333 0.3333333 0.5833333
              ## 2 b 0.13333333 0.3333333 0.5333333
              ## 3 c 0.16666667 0.3333333 0.5000000






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 16 '13 at 9:06









              Chinmay Patil

              13.4k42954




              13.4k42954












              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
                – Jaap
                Nov 22 at 9:47




















              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
                – Jaap
                Nov 22 at 9:47


















              an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
              – Jaap
              Nov 22 at 9:47






              an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])
              – Jaap
              Nov 22 at 9:47












              up vote
              6
              down vote













              Another alternative using sweep



              sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
              val0 val1 val2
              1 0.08333333 0.3333333 0.5833333
              2 0.13333333 0.3333333 0.5333333
              3 0.16666667 0.3333333 0.5000000





              share|improve this answer

























                up vote
                6
                down vote













                Another alternative using sweep



                sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
                val0 val1 val2
                1 0.08333333 0.3333333 0.5833333
                2 0.13333333 0.3333333 0.5333333
                3 0.16666667 0.3333333 0.5000000





                share|improve this answer























                  up vote
                  6
                  down vote










                  up vote
                  6
                  down vote









                  Another alternative using sweep



                  sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
                  val0 val1 val2
                  1 0.08333333 0.3333333 0.5833333
                  2 0.13333333 0.3333333 0.5333333
                  3 0.16666667 0.3333333 0.5000000





                  share|improve this answer












                  Another alternative using sweep



                  sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
                  val0 val1 val2
                  1 0.08333333 0.3333333 0.5833333
                  2 0.13333333 0.3333333 0.5333333
                  3 0.16666667 0.3333333 0.5000000






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 16 '13 at 9:19









                  Jilber Urbina

                  41.9k479113




                  41.9k479113






















                      up vote
                      4
                      down vote













                      The function adorn_percentages() from the janitor package does this:



                      library(janitor)
                      x %>% adorn_percentages()
                      id val0 val1 val2
                      a 0.08333333 0.3333333 0.5833333
                      b 0.13333333 0.3333333 0.5333333
                      c 0.16666667 0.3333333 0.5000000


                      This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.



                      Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.






                      share|improve this answer



























                        up vote
                        4
                        down vote













                        The function adorn_percentages() from the janitor package does this:



                        library(janitor)
                        x %>% adorn_percentages()
                        id val0 val1 val2
                        a 0.08333333 0.3333333 0.5833333
                        b 0.13333333 0.3333333 0.5333333
                        c 0.16666667 0.3333333 0.5000000


                        This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.



                        Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.






                        share|improve this answer

























                          up vote
                          4
                          down vote










                          up vote
                          4
                          down vote









                          The function adorn_percentages() from the janitor package does this:



                          library(janitor)
                          x %>% adorn_percentages()
                          id val0 val1 val2
                          a 0.08333333 0.3333333 0.5833333
                          b 0.13333333 0.3333333 0.5333333
                          c 0.16666667 0.3333333 0.5000000


                          This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.



                          Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.






                          share|improve this answer














                          The function adorn_percentages() from the janitor package does this:



                          library(janitor)
                          x %>% adorn_percentages()
                          id val0 val1 val2
                          a 0.08333333 0.3333333 0.5833333
                          b 0.13333333 0.3333333 0.5333333
                          c 0.16666667 0.3333333 0.5000000


                          This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.



                          Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Oct 9 at 1:56

























                          answered Oct 13 '16 at 20:36









                          Sam Firke

                          9,50625167




                          9,50625167






























                              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%2f16032826%2fcalculate-row-wise-proportions%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

                              Contact image not getting when fetch all contact list from iPhone by CNContact

                              count number of partitions of a set with n elements into k subsets

                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks