Calculate row-wise proportions





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







14















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































    14















    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



























      14












      14








      14


      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

      42.6k994111




      42.6k994111










      asked Apr 16 '13 at 9:02









      Rachit AgrawalRachit Agrawal

      1,48452148




      1,48452148
























          4 Answers
          4






          active

          oldest

          votes


















          8














          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



















          11














          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 '18 at 9:47





















          6














          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































            4














            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',
              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%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









              8














              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
















              8














              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














              8












              8








              8







              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









              A5C1D2H2I1M1N2O1R2T1A5C1D2H2I1M1N2O1R2T1

              155k19293388




              155k19293388








              • 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













              11














              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 '18 at 9:47


















              11














              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 '18 at 9:47
















              11












              11








              11







              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 PatilChinmay Patil

              13.7k42954




              13.7k42954













              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])

                – Jaap
                Nov 22 '18 at 9:47





















              • an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])

                – Jaap
                Nov 22 '18 at 9:47



















              an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])

              – Jaap
              Nov 22 '18 at 9:47







              an alternative to using cbind: x[-1] <- x[-1] / rowSums(x[-1])

              – Jaap
              Nov 22 '18 at 9:47













              6














              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




























                6














                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


























                  6












                  6








                  6







                  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 UrbinaJilber Urbina

                  43.6k484114




                  43.6k484114























                      4














                      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






























                        4














                        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




























                          4












                          4








                          4







                          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 '18 at 1:56

























                          answered Oct 13 '16 at 20:36









                          Sam FirkeSam Firke

                          10.5k35569




                          10.5k35569






























                              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.




                              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

                              Guess what letter conforming each word

                              Port of Spain

                              Run scheduled task as local user group (not BUILTIN)