Efficient method for Iterating over rows and replace by get column method in a data table?












-1















I am trying to iterate every rows and calculate Value from Columns A to E and corresponding column name from WhichCol. It works, but this step takes so long for 50,000 rows data. Is there an efficient way to do this?



library(data.table)
df<-structure(list(Id = 1:10, A = c(73L, 61L, 46L, 26L, 18L, 29L,
88L, 18L, 56L, 81L), B = c(68L, 49L, 27L, 10L, 37L, 72L, 71L,
60L, 52L, 62L), C = c(98L, 59L, 76L, 46L, 46L, 31L, 77L, 83L,
51L, 6L), D = c(40L, 18L, 27L, 18L, 72L, 95L, 87L, 29L, 35L,
80L), E = c(74L, 87L, 27L, 98L, 54L, 91L, 100L, 71L, 13L, 15L
), WhichCol = c("A", "C", "E", "B", "A", "D", "A", "C", "E",
"B"), Value = c(73L, 59L, 27L, 10L, 18L, 95L, 88L, 83L, 13L,
62L)), .Names = c("Id", "A", "B", "C", "D", "E", "WhichCol",
"Value"), class = "data.frame")

setDT(df)
df[["Value"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] })


Value column is added in the sample data here - but that's what I am trying to get..










share|improve this question





























    -1















    I am trying to iterate every rows and calculate Value from Columns A to E and corresponding column name from WhichCol. It works, but this step takes so long for 50,000 rows data. Is there an efficient way to do this?



    library(data.table)
    df<-structure(list(Id = 1:10, A = c(73L, 61L, 46L, 26L, 18L, 29L,
    88L, 18L, 56L, 81L), B = c(68L, 49L, 27L, 10L, 37L, 72L, 71L,
    60L, 52L, 62L), C = c(98L, 59L, 76L, 46L, 46L, 31L, 77L, 83L,
    51L, 6L), D = c(40L, 18L, 27L, 18L, 72L, 95L, 87L, 29L, 35L,
    80L), E = c(74L, 87L, 27L, 98L, 54L, 91L, 100L, 71L, 13L, 15L
    ), WhichCol = c("A", "C", "E", "B", "A", "D", "A", "C", "E",
    "B"), Value = c(73L, 59L, 27L, 10L, 18L, 95L, 88L, 83L, 13L,
    62L)), .Names = c("Id", "A", "B", "C", "D", "E", "WhichCol",
    "Value"), class = "data.frame")

    setDT(df)
    df[["Value"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] })


    Value column is added in the sample data here - but that's what I am trying to get..










    share|improve this question



























      -1












      -1








      -1








      I am trying to iterate every rows and calculate Value from Columns A to E and corresponding column name from WhichCol. It works, but this step takes so long for 50,000 rows data. Is there an efficient way to do this?



      library(data.table)
      df<-structure(list(Id = 1:10, A = c(73L, 61L, 46L, 26L, 18L, 29L,
      88L, 18L, 56L, 81L), B = c(68L, 49L, 27L, 10L, 37L, 72L, 71L,
      60L, 52L, 62L), C = c(98L, 59L, 76L, 46L, 46L, 31L, 77L, 83L,
      51L, 6L), D = c(40L, 18L, 27L, 18L, 72L, 95L, 87L, 29L, 35L,
      80L), E = c(74L, 87L, 27L, 98L, 54L, 91L, 100L, 71L, 13L, 15L
      ), WhichCol = c("A", "C", "E", "B", "A", "D", "A", "C", "E",
      "B"), Value = c(73L, 59L, 27L, 10L, 18L, 95L, 88L, 83L, 13L,
      62L)), .Names = c("Id", "A", "B", "C", "D", "E", "WhichCol",
      "Value"), class = "data.frame")

      setDT(df)
      df[["Value"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] })


      Value column is added in the sample data here - but that's what I am trying to get..










      share|improve this question
















      I am trying to iterate every rows and calculate Value from Columns A to E and corresponding column name from WhichCol. It works, but this step takes so long for 50,000 rows data. Is there an efficient way to do this?



      library(data.table)
      df<-structure(list(Id = 1:10, A = c(73L, 61L, 46L, 26L, 18L, 29L,
      88L, 18L, 56L, 81L), B = c(68L, 49L, 27L, 10L, 37L, 72L, 71L,
      60L, 52L, 62L), C = c(98L, 59L, 76L, 46L, 46L, 31L, 77L, 83L,
      51L, 6L), D = c(40L, 18L, 27L, 18L, 72L, 95L, 87L, 29L, 35L,
      80L), E = c(74L, 87L, 27L, 98L, 54L, 91L, 100L, 71L, 13L, 15L
      ), WhichCol = c("A", "C", "E", "B", "A", "D", "A", "C", "E",
      "B"), Value = c(73L, 59L, 27L, 10L, 18L, 95L, 88L, 83L, 13L,
      62L)), .Names = c("Id", "A", "B", "C", "D", "E", "WhichCol",
      "Value"), class = "data.frame")

      setDT(df)
      df[["Value"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] })


      Value column is added in the sample data here - but that's what I am trying to get..







      r data.table






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 7:58









      LAP

      5,7902723




      5,7902723










      asked Nov 16 '18 at 5:57









      JeanVudaJeanVuda

      1,011623




      1,011623
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You could instead of looping over each row, use the fact, that for each value of WhichCol you know which colum you want. (e.g. for every WhichCol == "A" take column A).



          df[, ValueNew := get(unique(WhichCol)), by = WhichCol]



          I did a little speed test:



           n <- 1000
          df <- rbindlist(rep(list(df), n))

          # over unique WhichCol

          system.time(df[, ValueNew := get(unique(WhichCol)), by = WhichCol])
          user system elapsed
          0.002 0.000 0.001

          system.time(df[["Value2"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] }))
          user system elapsed
          5.445 0.021 5.472


          I hope this will help you.






          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%2f53332221%2fefficient-method-for-iterating-over-rows-and-replace-by-get-column-method-in-a-d%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














            You could instead of looping over each row, use the fact, that for each value of WhichCol you know which colum you want. (e.g. for every WhichCol == "A" take column A).



            df[, ValueNew := get(unique(WhichCol)), by = WhichCol]



            I did a little speed test:



             n <- 1000
            df <- rbindlist(rep(list(df), n))

            # over unique WhichCol

            system.time(df[, ValueNew := get(unique(WhichCol)), by = WhichCol])
            user system elapsed
            0.002 0.000 0.001

            system.time(df[["Value2"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] }))
            user system elapsed
            5.445 0.021 5.472


            I hope this will help you.






            share|improve this answer




























              1














              You could instead of looping over each row, use the fact, that for each value of WhichCol you know which colum you want. (e.g. for every WhichCol == "A" take column A).



              df[, ValueNew := get(unique(WhichCol)), by = WhichCol]



              I did a little speed test:



               n <- 1000
              df <- rbindlist(rep(list(df), n))

              # over unique WhichCol

              system.time(df[, ValueNew := get(unique(WhichCol)), by = WhichCol])
              user system elapsed
              0.002 0.000 0.001

              system.time(df[["Value2"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] }))
              user system elapsed
              5.445 0.021 5.472


              I hope this will help you.






              share|improve this answer


























                1












                1








                1







                You could instead of looping over each row, use the fact, that for each value of WhichCol you know which colum you want. (e.g. for every WhichCol == "A" take column A).



                df[, ValueNew := get(unique(WhichCol)), by = WhichCol]



                I did a little speed test:



                 n <- 1000
                df <- rbindlist(rep(list(df), n))

                # over unique WhichCol

                system.time(df[, ValueNew := get(unique(WhichCol)), by = WhichCol])
                user system elapsed
                0.002 0.000 0.001

                system.time(df[["Value2"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] }))
                user system elapsed
                5.445 0.021 5.472


                I hope this will help you.






                share|improve this answer













                You could instead of looping over each row, use the fact, that for each value of WhichCol you know which colum you want. (e.g. for every WhichCol == "A" take column A).



                df[, ValueNew := get(unique(WhichCol)), by = WhichCol]



                I did a little speed test:



                 n <- 1000
                df <- rbindlist(rep(list(df), n))

                # over unique WhichCol

                system.time(df[, ValueNew := get(unique(WhichCol)), by = WhichCol])
                user system elapsed
                0.002 0.000 0.001

                system.time(df[["Value2"]]<-sapply(1:nrow(df), function(x){ df[x, get(WhichCol)] }))
                user system elapsed
                5.445 0.021 5.472


                I hope this will help you.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 16:22









                Jakob GeppJakob Gepp

                16818




                16818
































                    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%2f53332221%2fefficient-method-for-iterating-over-rows-and-replace-by-get-column-method-in-a-d%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

                    List item for chat from Array inside array React Native

                    Thiostrepton

                    Caerphilly