Efficiently summarizing and transforming a table of data using tidyverse functions












-1















I have a relatively large data file that looks like (a), and need create a structure like (b). Thus I need to calculate the sum of Amount times Coeficient for each ID and each year.



enter image description here



I quickly hacked something together using nested for loops, but thats of course terribly inefficient:



library(tidyverse)

data <- tibble(
id=c("A", "B", "C", "A", "A", "B", "C"),
year=c(2002,2002,2004,2002,2003,2003,2005),
amount=c(1000,1500,1000,500,1000,1000,500),
coef=rep(0.5,7)
)

years <- sort(unique(data$year))
ids <- unique(data$id)

result <- matrix(0,length(ids),length(years)) %>%
as.tibble() %>% setNames(., years)

for (i in seq_along(ids)){
for (j in seq_along(years)){
d <- filter(data, id==ids[i] & year== years[j])
if (nrow(d)!=0){
result[i,j] <- sum(d$amount*d$coef)
}
}
}
result <- add_column(result, ID=ids, .before = 1)


I was wondering how one could solve this efficiently using map(), group_by() or any other tidyverse functions.



Thanks in advance for helpful suggestions.










share|improve this question


















  • 4





    look up "long to wide [r] [[tidyverse]".

    – 42-
    Dec 31 '18 at 21:21






  • 2





    ?spread will get you there

    – svenhalvorson
    Dec 31 '18 at 21:23
















-1















I have a relatively large data file that looks like (a), and need create a structure like (b). Thus I need to calculate the sum of Amount times Coeficient for each ID and each year.



enter image description here



I quickly hacked something together using nested for loops, but thats of course terribly inefficient:



library(tidyverse)

data <- tibble(
id=c("A", "B", "C", "A", "A", "B", "C"),
year=c(2002,2002,2004,2002,2003,2003,2005),
amount=c(1000,1500,1000,500,1000,1000,500),
coef=rep(0.5,7)
)

years <- sort(unique(data$year))
ids <- unique(data$id)

result <- matrix(0,length(ids),length(years)) %>%
as.tibble() %>% setNames(., years)

for (i in seq_along(ids)){
for (j in seq_along(years)){
d <- filter(data, id==ids[i] & year== years[j])
if (nrow(d)!=0){
result[i,j] <- sum(d$amount*d$coef)
}
}
}
result <- add_column(result, ID=ids, .before = 1)


I was wondering how one could solve this efficiently using map(), group_by() or any other tidyverse functions.



Thanks in advance for helpful suggestions.










share|improve this question


















  • 4





    look up "long to wide [r] [[tidyverse]".

    – 42-
    Dec 31 '18 at 21:21






  • 2





    ?spread will get you there

    – svenhalvorson
    Dec 31 '18 at 21:23














-1












-1








-1








I have a relatively large data file that looks like (a), and need create a structure like (b). Thus I need to calculate the sum of Amount times Coeficient for each ID and each year.



enter image description here



I quickly hacked something together using nested for loops, but thats of course terribly inefficient:



library(tidyverse)

data <- tibble(
id=c("A", "B", "C", "A", "A", "B", "C"),
year=c(2002,2002,2004,2002,2003,2003,2005),
amount=c(1000,1500,1000,500,1000,1000,500),
coef=rep(0.5,7)
)

years <- sort(unique(data$year))
ids <- unique(data$id)

result <- matrix(0,length(ids),length(years)) %>%
as.tibble() %>% setNames(., years)

for (i in seq_along(ids)){
for (j in seq_along(years)){
d <- filter(data, id==ids[i] & year== years[j])
if (nrow(d)!=0){
result[i,j] <- sum(d$amount*d$coef)
}
}
}
result <- add_column(result, ID=ids, .before = 1)


I was wondering how one could solve this efficiently using map(), group_by() or any other tidyverse functions.



Thanks in advance for helpful suggestions.










share|improve this question














I have a relatively large data file that looks like (a), and need create a structure like (b). Thus I need to calculate the sum of Amount times Coeficient for each ID and each year.



enter image description here



I quickly hacked something together using nested for loops, but thats of course terribly inefficient:



library(tidyverse)

data <- tibble(
id=c("A", "B", "C", "A", "A", "B", "C"),
year=c(2002,2002,2004,2002,2003,2003,2005),
amount=c(1000,1500,1000,500,1000,1000,500),
coef=rep(0.5,7)
)

years <- sort(unique(data$year))
ids <- unique(data$id)

result <- matrix(0,length(ids),length(years)) %>%
as.tibble() %>% setNames(., years)

for (i in seq_along(ids)){
for (j in seq_along(years)){
d <- filter(data, id==ids[i] & year== years[j])
if (nrow(d)!=0){
result[i,j] <- sum(d$amount*d$coef)
}
}
}
result <- add_column(result, ID=ids, .before = 1)


I was wondering how one could solve this efficiently using map(), group_by() or any other tidyverse functions.



Thanks in advance for helpful suggestions.







r tidyverse purrr






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 31 '18 at 21:20









FlorianFlorian

255




255








  • 4





    look up "long to wide [r] [[tidyverse]".

    – 42-
    Dec 31 '18 at 21:21






  • 2





    ?spread will get you there

    – svenhalvorson
    Dec 31 '18 at 21:23














  • 4





    look up "long to wide [r] [[tidyverse]".

    – 42-
    Dec 31 '18 at 21:21






  • 2





    ?spread will get you there

    – svenhalvorson
    Dec 31 '18 at 21:23








4




4





look up "long to wide [r] [[tidyverse]".

– 42-
Dec 31 '18 at 21:21





look up "long to wide [r] [[tidyverse]".

– 42-
Dec 31 '18 at 21:21




2




2





?spread will get you there

– svenhalvorson
Dec 31 '18 at 21:23





?spread will get you there

– svenhalvorson
Dec 31 '18 at 21:23












2 Answers
2






active

oldest

votes


















1














Here's one way that seems to work. I'm sure there are others.



library(tidyverse)

id <- c("A", "B", "C", "A", "A", "B", "C")
year <- c(2002,2002,2004,2002,2003,2003,2005)
amount <- c(1000,1500,1000,500,1000,1000,500)
coef <- rep(0.5,7)

data <- tibble(id, year, amount, coef)

table <- data %>%
group_by(., id, year) %>%
mutate(prod = amount*coef)%>%
summarize(., sumprod = sum(prod)) %>%
spread(., year, sumprod) %>%
replace(is.na(.), 0)





share|improve this answer
























  • Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

    – Steph
    Dec 31 '18 at 23:16











  • Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

    – Florian
    Jan 1 at 0:18



















1














Thanks for the hint, this really is just one line:



result  <- data %>% group_by(id, year) %>% summarise(S=sum(amount*coef)) %>% spread(year, S)





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%2f53991494%2fefficiently-summarizing-and-transforming-a-table-of-data-using-tidyverse-functio%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Here's one way that seems to work. I'm sure there are others.



    library(tidyverse)

    id <- c("A", "B", "C", "A", "A", "B", "C")
    year <- c(2002,2002,2004,2002,2003,2003,2005)
    amount <- c(1000,1500,1000,500,1000,1000,500)
    coef <- rep(0.5,7)

    data <- tibble(id, year, amount, coef)

    table <- data %>%
    group_by(., id, year) %>%
    mutate(prod = amount*coef)%>%
    summarize(., sumprod = sum(prod)) %>%
    spread(., year, sumprod) %>%
    replace(is.na(.), 0)





    share|improve this answer
























    • Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

      – Steph
      Dec 31 '18 at 23:16











    • Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

      – Florian
      Jan 1 at 0:18
















    1














    Here's one way that seems to work. I'm sure there are others.



    library(tidyverse)

    id <- c("A", "B", "C", "A", "A", "B", "C")
    year <- c(2002,2002,2004,2002,2003,2003,2005)
    amount <- c(1000,1500,1000,500,1000,1000,500)
    coef <- rep(0.5,7)

    data <- tibble(id, year, amount, coef)

    table <- data %>%
    group_by(., id, year) %>%
    mutate(prod = amount*coef)%>%
    summarize(., sumprod = sum(prod)) %>%
    spread(., year, sumprod) %>%
    replace(is.na(.), 0)





    share|improve this answer
























    • Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

      – Steph
      Dec 31 '18 at 23:16











    • Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

      – Florian
      Jan 1 at 0:18














    1












    1








    1







    Here's one way that seems to work. I'm sure there are others.



    library(tidyverse)

    id <- c("A", "B", "C", "A", "A", "B", "C")
    year <- c(2002,2002,2004,2002,2003,2003,2005)
    amount <- c(1000,1500,1000,500,1000,1000,500)
    coef <- rep(0.5,7)

    data <- tibble(id, year, amount, coef)

    table <- data %>%
    group_by(., id, year) %>%
    mutate(prod = amount*coef)%>%
    summarize(., sumprod = sum(prod)) %>%
    spread(., year, sumprod) %>%
    replace(is.na(.), 0)





    share|improve this answer













    Here's one way that seems to work. I'm sure there are others.



    library(tidyverse)

    id <- c("A", "B", "C", "A", "A", "B", "C")
    year <- c(2002,2002,2004,2002,2003,2003,2005)
    amount <- c(1000,1500,1000,500,1000,1000,500)
    coef <- rep(0.5,7)

    data <- tibble(id, year, amount, coef)

    table <- data %>%
    group_by(., id, year) %>%
    mutate(prod = amount*coef)%>%
    summarize(., sumprod = sum(prod)) %>%
    spread(., year, sumprod) %>%
    replace(is.na(.), 0)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 31 '18 at 23:12









    StephSteph

    415




    415













    • Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

      – Steph
      Dec 31 '18 at 23:16











    • Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

      – Florian
      Jan 1 at 0:18



















    • Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

      – Steph
      Dec 31 '18 at 23:16











    • Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

      – Florian
      Jan 1 at 0:18

















    Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

    – Steph
    Dec 31 '18 at 23:16





    Ha ha...oops. I posted mine before I realized you'd cracked it. Good illustration that you can usually get to the same place in different ways. :-)

    – Steph
    Dec 31 '18 at 23:16













    Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

    – Florian
    Jan 1 at 0:18





    Thanks, I'm still new to the tidyverse so seeing a different way is helpful ;-)

    – Florian
    Jan 1 at 0:18













    1














    Thanks for the hint, this really is just one line:



    result  <- data %>% group_by(id, year) %>% summarise(S=sum(amount*coef)) %>% spread(year, S)





    share|improve this answer




























      1














      Thanks for the hint, this really is just one line:



      result  <- data %>% group_by(id, year) %>% summarise(S=sum(amount*coef)) %>% spread(year, S)





      share|improve this answer


























        1












        1








        1







        Thanks for the hint, this really is just one line:



        result  <- data %>% group_by(id, year) %>% summarise(S=sum(amount*coef)) %>% spread(year, S)





        share|improve this answer













        Thanks for the hint, this really is just one line:



        result  <- data %>% group_by(id, year) %>% summarise(S=sum(amount*coef)) %>% spread(year, S)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 22:15









        FlorianFlorian

        255




        255






























            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%2f53991494%2fefficiently-summarizing-and-transforming-a-table-of-data-using-tidyverse-functio%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

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas