Automatic updating criteria for summarizing a data frame












1














I have a vector with a bunch of criteria that I want to use to cycle through my data frame summarizing my relevant data column.



I reproduce bellow my code, using dplyr and pipe. It works perfectly, so I'll explain my struggle bellow it.



My code:



c1 <- c(0.5,0.5,0.5,1,1,1,2,2,2,2.5,2.5,2,3,3,4,4,4.4,4.5,4.5,5,5.5,6,7,7,8,8.5,9,9.5)
c2 <- c(12,10,40,4,12,7,3,2,1,4,8,10,10,7,7,4,4,4,5,5,6,15,15,25,4,4,7,18)
c3 <- rep(c("AA","BB","CC","DD"), 7)

df <- data.frame(criteria.names = c3, criteria.data = c1, relevant.data = c2,
stringsAsFactors = FALSE)

user.criteria <- c(0,2,3,5,7,10)


summarised.data <- df %>%
group_by(criteria.names) %>%
summarise(class1 = sum(relevant.data[criteria.data >= 0 & criteria.data < 2]),
class2 = sum(relevant.data[criteria.data >= 2 & criteria.data < 3]),
class3 = sum(relevant.data[criteria.data >= 3 & criteria.data < 5]),
class4 = sum(relevant.data[criteria.data >= 5 & criteria.data < 7]),
class5 = sum(relevant.data[criteria.data >= 7 & criteria.data < 10]))


Here's my expected output:



 summarised.data
# A tibble: 4 x 6
criteria.names class1 class2 class3 class4 class5
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 AA 24 1 14 6 4
2 BB 17 4 11 15 4
3 CC 40 11 12 0 22
4 DD 4 12 4 5 43


MY PROBLEM IS: my "user.criteria" vector, whose values I use in my summarization, is gonna come via user input, so there's no guarantee that they are actually going to provide me with the 2,3,5,7,10 values (0 is always going to be there by default) I've explicitly put in my calculations. I've tried using the apply family functions (apply, sapply, lapply, mapply) and adply (plyr package) but so far I haven't been successful in tackling this problem. I'm trying to avoid using explicit loops in R, as the actual database I'm working with is quite huge.



Bellow is an example of my faulty code:



summarised.try <- 1:(length(user.criteria)-1) %>%
adply(1,function(x){
df %>%
group_by(criteria.names) %>%
summarise(class = sum(relevant.data[criteria.data >=user.criteria[x]
& criteria.data < user.criteria[x+1]]))})


What I want is to find an elegant way to get the values my user provides me and use them to automatically calculate my summarization, without needing to manually edit my code. Tks!










share|improve this question



























    1














    I have a vector with a bunch of criteria that I want to use to cycle through my data frame summarizing my relevant data column.



    I reproduce bellow my code, using dplyr and pipe. It works perfectly, so I'll explain my struggle bellow it.



    My code:



    c1 <- c(0.5,0.5,0.5,1,1,1,2,2,2,2.5,2.5,2,3,3,4,4,4.4,4.5,4.5,5,5.5,6,7,7,8,8.5,9,9.5)
    c2 <- c(12,10,40,4,12,7,3,2,1,4,8,10,10,7,7,4,4,4,5,5,6,15,15,25,4,4,7,18)
    c3 <- rep(c("AA","BB","CC","DD"), 7)

    df <- data.frame(criteria.names = c3, criteria.data = c1, relevant.data = c2,
    stringsAsFactors = FALSE)

    user.criteria <- c(0,2,3,5,7,10)


    summarised.data <- df %>%
    group_by(criteria.names) %>%
    summarise(class1 = sum(relevant.data[criteria.data >= 0 & criteria.data < 2]),
    class2 = sum(relevant.data[criteria.data >= 2 & criteria.data < 3]),
    class3 = sum(relevant.data[criteria.data >= 3 & criteria.data < 5]),
    class4 = sum(relevant.data[criteria.data >= 5 & criteria.data < 7]),
    class5 = sum(relevant.data[criteria.data >= 7 & criteria.data < 10]))


    Here's my expected output:



     summarised.data
    # A tibble: 4 x 6
    criteria.names class1 class2 class3 class4 class5
    <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
    1 AA 24 1 14 6 4
    2 BB 17 4 11 15 4
    3 CC 40 11 12 0 22
    4 DD 4 12 4 5 43


    MY PROBLEM IS: my "user.criteria" vector, whose values I use in my summarization, is gonna come via user input, so there's no guarantee that they are actually going to provide me with the 2,3,5,7,10 values (0 is always going to be there by default) I've explicitly put in my calculations. I've tried using the apply family functions (apply, sapply, lapply, mapply) and adply (plyr package) but so far I haven't been successful in tackling this problem. I'm trying to avoid using explicit loops in R, as the actual database I'm working with is quite huge.



    Bellow is an example of my faulty code:



    summarised.try <- 1:(length(user.criteria)-1) %>%
    adply(1,function(x){
    df %>%
    group_by(criteria.names) %>%
    summarise(class = sum(relevant.data[criteria.data >=user.criteria[x]
    & criteria.data < user.criteria[x+1]]))})


    What I want is to find an elegant way to get the values my user provides me and use them to automatically calculate my summarization, without needing to manually edit my code. Tks!










    share|improve this question

























      1












      1








      1







      I have a vector with a bunch of criteria that I want to use to cycle through my data frame summarizing my relevant data column.



      I reproduce bellow my code, using dplyr and pipe. It works perfectly, so I'll explain my struggle bellow it.



      My code:



      c1 <- c(0.5,0.5,0.5,1,1,1,2,2,2,2.5,2.5,2,3,3,4,4,4.4,4.5,4.5,5,5.5,6,7,7,8,8.5,9,9.5)
      c2 <- c(12,10,40,4,12,7,3,2,1,4,8,10,10,7,7,4,4,4,5,5,6,15,15,25,4,4,7,18)
      c3 <- rep(c("AA","BB","CC","DD"), 7)

      df <- data.frame(criteria.names = c3, criteria.data = c1, relevant.data = c2,
      stringsAsFactors = FALSE)

      user.criteria <- c(0,2,3,5,7,10)


      summarised.data <- df %>%
      group_by(criteria.names) %>%
      summarise(class1 = sum(relevant.data[criteria.data >= 0 & criteria.data < 2]),
      class2 = sum(relevant.data[criteria.data >= 2 & criteria.data < 3]),
      class3 = sum(relevant.data[criteria.data >= 3 & criteria.data < 5]),
      class4 = sum(relevant.data[criteria.data >= 5 & criteria.data < 7]),
      class5 = sum(relevant.data[criteria.data >= 7 & criteria.data < 10]))


      Here's my expected output:



       summarised.data
      # A tibble: 4 x 6
      criteria.names class1 class2 class3 class4 class5
      <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
      1 AA 24 1 14 6 4
      2 BB 17 4 11 15 4
      3 CC 40 11 12 0 22
      4 DD 4 12 4 5 43


      MY PROBLEM IS: my "user.criteria" vector, whose values I use in my summarization, is gonna come via user input, so there's no guarantee that they are actually going to provide me with the 2,3,5,7,10 values (0 is always going to be there by default) I've explicitly put in my calculations. I've tried using the apply family functions (apply, sapply, lapply, mapply) and adply (plyr package) but so far I haven't been successful in tackling this problem. I'm trying to avoid using explicit loops in R, as the actual database I'm working with is quite huge.



      Bellow is an example of my faulty code:



      summarised.try <- 1:(length(user.criteria)-1) %>%
      adply(1,function(x){
      df %>%
      group_by(criteria.names) %>%
      summarise(class = sum(relevant.data[criteria.data >=user.criteria[x]
      & criteria.data < user.criteria[x+1]]))})


      What I want is to find an elegant way to get the values my user provides me and use them to automatically calculate my summarization, without needing to manually edit my code. Tks!










      share|improve this question













      I have a vector with a bunch of criteria that I want to use to cycle through my data frame summarizing my relevant data column.



      I reproduce bellow my code, using dplyr and pipe. It works perfectly, so I'll explain my struggle bellow it.



      My code:



      c1 <- c(0.5,0.5,0.5,1,1,1,2,2,2,2.5,2.5,2,3,3,4,4,4.4,4.5,4.5,5,5.5,6,7,7,8,8.5,9,9.5)
      c2 <- c(12,10,40,4,12,7,3,2,1,4,8,10,10,7,7,4,4,4,5,5,6,15,15,25,4,4,7,18)
      c3 <- rep(c("AA","BB","CC","DD"), 7)

      df <- data.frame(criteria.names = c3, criteria.data = c1, relevant.data = c2,
      stringsAsFactors = FALSE)

      user.criteria <- c(0,2,3,5,7,10)


      summarised.data <- df %>%
      group_by(criteria.names) %>%
      summarise(class1 = sum(relevant.data[criteria.data >= 0 & criteria.data < 2]),
      class2 = sum(relevant.data[criteria.data >= 2 & criteria.data < 3]),
      class3 = sum(relevant.data[criteria.data >= 3 & criteria.data < 5]),
      class4 = sum(relevant.data[criteria.data >= 5 & criteria.data < 7]),
      class5 = sum(relevant.data[criteria.data >= 7 & criteria.data < 10]))


      Here's my expected output:



       summarised.data
      # A tibble: 4 x 6
      criteria.names class1 class2 class3 class4 class5
      <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
      1 AA 24 1 14 6 4
      2 BB 17 4 11 15 4
      3 CC 40 11 12 0 22
      4 DD 4 12 4 5 43


      MY PROBLEM IS: my "user.criteria" vector, whose values I use in my summarization, is gonna come via user input, so there's no guarantee that they are actually going to provide me with the 2,3,5,7,10 values (0 is always going to be there by default) I've explicitly put in my calculations. I've tried using the apply family functions (apply, sapply, lapply, mapply) and adply (plyr package) but so far I haven't been successful in tackling this problem. I'm trying to avoid using explicit loops in R, as the actual database I'm working with is quite huge.



      Bellow is an example of my faulty code:



      summarised.try <- 1:(length(user.criteria)-1) %>%
      adply(1,function(x){
      df %>%
      group_by(criteria.names) %>%
      summarise(class = sum(relevant.data[criteria.data >=user.criteria[x]
      & criteria.data < user.criteria[x+1]]))})


      What I want is to find an elegant way to get the values my user provides me and use them to automatically calculate my summarization, without needing to manually edit my code. Tks!







      r loops dataframe criteria summarization






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 at 19:38









      Bruno Assunção

      234




      234
























          1 Answer
          1






          active

          oldest

          votes


















          0














          This function might be the least elegant solution, however it works if we keep same df's column names (i.e. criteria.names, criteria.data, relevant.data ):



          library(dplyr)

          classifier <- function(criteria, df){

          classified_columns = list()

          for(i in 1:length(criteria) ){

          tmp_class = vector("numeric")

          for( ii in unique(df$criteria.names) ){

          tmp_df = df[df$criteria.names == ii,]

          if ( i + 1 <= length(criteria) ){

          tmp_df %>%
          summarise(n = relevant.data[criteria.data >= criteria[i] & criteria.data < criteria[i + 1]] %>%
          sum() ) %>%
          .$n %>%
          append(x = tmp_class, values = .) -> tmp_class
          }
          }

          if( length(tmp_class) > 0 ){

          classified_columns[[paste("class", i, sep = "")]] = tmp_class
          }
          }

          data.frame(criteria.names = unique(df$criteria.names),
          as.data.frame(classified_columns)) %>%
          return(.)
          }


          Testing function:



          classifier(criteria = user.criteria, df = df)


          Output:



             criteria.names class1 class2 class3 class4 class5
          1 AA 24 1 14 6 4
          2 BB 17 4 11 15 4
          3 CC 40 11 12 0 22
          4 DD 4 12 4 5 43





          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%2f53307625%2fautomatic-updating-criteria-for-summarizing-a-data-frame%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









            0














            This function might be the least elegant solution, however it works if we keep same df's column names (i.e. criteria.names, criteria.data, relevant.data ):



            library(dplyr)

            classifier <- function(criteria, df){

            classified_columns = list()

            for(i in 1:length(criteria) ){

            tmp_class = vector("numeric")

            for( ii in unique(df$criteria.names) ){

            tmp_df = df[df$criteria.names == ii,]

            if ( i + 1 <= length(criteria) ){

            tmp_df %>%
            summarise(n = relevant.data[criteria.data >= criteria[i] & criteria.data < criteria[i + 1]] %>%
            sum() ) %>%
            .$n %>%
            append(x = tmp_class, values = .) -> tmp_class
            }
            }

            if( length(tmp_class) > 0 ){

            classified_columns[[paste("class", i, sep = "")]] = tmp_class
            }
            }

            data.frame(criteria.names = unique(df$criteria.names),
            as.data.frame(classified_columns)) %>%
            return(.)
            }


            Testing function:



            classifier(criteria = user.criteria, df = df)


            Output:



               criteria.names class1 class2 class3 class4 class5
            1 AA 24 1 14 6 4
            2 BB 17 4 11 15 4
            3 CC 40 11 12 0 22
            4 DD 4 12 4 5 43





            share|improve this answer


























              0














              This function might be the least elegant solution, however it works if we keep same df's column names (i.e. criteria.names, criteria.data, relevant.data ):



              library(dplyr)

              classifier <- function(criteria, df){

              classified_columns = list()

              for(i in 1:length(criteria) ){

              tmp_class = vector("numeric")

              for( ii in unique(df$criteria.names) ){

              tmp_df = df[df$criteria.names == ii,]

              if ( i + 1 <= length(criteria) ){

              tmp_df %>%
              summarise(n = relevant.data[criteria.data >= criteria[i] & criteria.data < criteria[i + 1]] %>%
              sum() ) %>%
              .$n %>%
              append(x = tmp_class, values = .) -> tmp_class
              }
              }

              if( length(tmp_class) > 0 ){

              classified_columns[[paste("class", i, sep = "")]] = tmp_class
              }
              }

              data.frame(criteria.names = unique(df$criteria.names),
              as.data.frame(classified_columns)) %>%
              return(.)
              }


              Testing function:



              classifier(criteria = user.criteria, df = df)


              Output:



                 criteria.names class1 class2 class3 class4 class5
              1 AA 24 1 14 6 4
              2 BB 17 4 11 15 4
              3 CC 40 11 12 0 22
              4 DD 4 12 4 5 43





              share|improve this answer
























                0












                0








                0






                This function might be the least elegant solution, however it works if we keep same df's column names (i.e. criteria.names, criteria.data, relevant.data ):



                library(dplyr)

                classifier <- function(criteria, df){

                classified_columns = list()

                for(i in 1:length(criteria) ){

                tmp_class = vector("numeric")

                for( ii in unique(df$criteria.names) ){

                tmp_df = df[df$criteria.names == ii,]

                if ( i + 1 <= length(criteria) ){

                tmp_df %>%
                summarise(n = relevant.data[criteria.data >= criteria[i] & criteria.data < criteria[i + 1]] %>%
                sum() ) %>%
                .$n %>%
                append(x = tmp_class, values = .) -> tmp_class
                }
                }

                if( length(tmp_class) > 0 ){

                classified_columns[[paste("class", i, sep = "")]] = tmp_class
                }
                }

                data.frame(criteria.names = unique(df$criteria.names),
                as.data.frame(classified_columns)) %>%
                return(.)
                }


                Testing function:



                classifier(criteria = user.criteria, df = df)


                Output:



                   criteria.names class1 class2 class3 class4 class5
                1 AA 24 1 14 6 4
                2 BB 17 4 11 15 4
                3 CC 40 11 12 0 22
                4 DD 4 12 4 5 43





                share|improve this answer












                This function might be the least elegant solution, however it works if we keep same df's column names (i.e. criteria.names, criteria.data, relevant.data ):



                library(dplyr)

                classifier <- function(criteria, df){

                classified_columns = list()

                for(i in 1:length(criteria) ){

                tmp_class = vector("numeric")

                for( ii in unique(df$criteria.names) ){

                tmp_df = df[df$criteria.names == ii,]

                if ( i + 1 <= length(criteria) ){

                tmp_df %>%
                summarise(n = relevant.data[criteria.data >= criteria[i] & criteria.data < criteria[i + 1]] %>%
                sum() ) %>%
                .$n %>%
                append(x = tmp_class, values = .) -> tmp_class
                }
                }

                if( length(tmp_class) > 0 ){

                classified_columns[[paste("class", i, sep = "")]] = tmp_class
                }
                }

                data.frame(criteria.names = unique(df$criteria.names),
                as.data.frame(classified_columns)) %>%
                return(.)
                }


                Testing function:



                classifier(criteria = user.criteria, df = df)


                Output:



                   criteria.names class1 class2 class3 class4 class5
                1 AA 24 1 14 6 4
                2 BB 17 4 11 15 4
                3 CC 40 11 12 0 22
                4 DD 4 12 4 5 43






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 at 4:45









                Ulises Rosas-Puchuri

                9915




                9915






























                    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%2f53307625%2fautomatic-updating-criteria-for-summarizing-a-data-frame%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