Adding a new column with mutate and group by












0















I want to create a new column called age based on a previous column and group by functions. The dataset is as follows:



tid<- c(1,2,3,4, 1,2,3,4,1,2,3,4)
active<- c(0,1,0,4, 0,0,0,1,0,0,1,0)
person<- c('John', 'John','John', 'John', 'Emma', 'Emma','Emma','Emma', 'Edward', 'Edward', 'Edward', 'Edward')
df<- data.frame(tid, active, person)


I want to create age which starts with 0 when the person is first active i.e., the value of active becomes greater than 0 for first time and then incrementally gets added with one value for the next record. Any suggestions?



I am expecting the output as follows:



 name     age 
John 0
John 0
John 1
John 2
Emma 0
Emma 0
Emma 0
Emma 0
Edward 0
Edward 0
Edward 0
Edward 1









share|improve this question























  • What have you tried? Please give us an example of some strategies / code you have attempted

    – sorearm
    Nov 19 '18 at 11:07











  • Shouldn't John be 0,0,1,1?

    – snoram
    Nov 19 '18 at 11:15











  • no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

    – user3570187
    Nov 19 '18 at 11:19
















0















I want to create a new column called age based on a previous column and group by functions. The dataset is as follows:



tid<- c(1,2,3,4, 1,2,3,4,1,2,3,4)
active<- c(0,1,0,4, 0,0,0,1,0,0,1,0)
person<- c('John', 'John','John', 'John', 'Emma', 'Emma','Emma','Emma', 'Edward', 'Edward', 'Edward', 'Edward')
df<- data.frame(tid, active, person)


I want to create age which starts with 0 when the person is first active i.e., the value of active becomes greater than 0 for first time and then incrementally gets added with one value for the next record. Any suggestions?



I am expecting the output as follows:



 name     age 
John 0
John 0
John 1
John 2
Emma 0
Emma 0
Emma 0
Emma 0
Edward 0
Edward 0
Edward 0
Edward 1









share|improve this question























  • What have you tried? Please give us an example of some strategies / code you have attempted

    – sorearm
    Nov 19 '18 at 11:07











  • Shouldn't John be 0,0,1,1?

    – snoram
    Nov 19 '18 at 11:15











  • no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

    – user3570187
    Nov 19 '18 at 11:19














0












0








0








I want to create a new column called age based on a previous column and group by functions. The dataset is as follows:



tid<- c(1,2,3,4, 1,2,3,4,1,2,3,4)
active<- c(0,1,0,4, 0,0,0,1,0,0,1,0)
person<- c('John', 'John','John', 'John', 'Emma', 'Emma','Emma','Emma', 'Edward', 'Edward', 'Edward', 'Edward')
df<- data.frame(tid, active, person)


I want to create age which starts with 0 when the person is first active i.e., the value of active becomes greater than 0 for first time and then incrementally gets added with one value for the next record. Any suggestions?



I am expecting the output as follows:



 name     age 
John 0
John 0
John 1
John 2
Emma 0
Emma 0
Emma 0
Emma 0
Edward 0
Edward 0
Edward 0
Edward 1









share|improve this question














I want to create a new column called age based on a previous column and group by functions. The dataset is as follows:



tid<- c(1,2,3,4, 1,2,3,4,1,2,3,4)
active<- c(0,1,0,4, 0,0,0,1,0,0,1,0)
person<- c('John', 'John','John', 'John', 'Emma', 'Emma','Emma','Emma', 'Edward', 'Edward', 'Edward', 'Edward')
df<- data.frame(tid, active, person)


I want to create age which starts with 0 when the person is first active i.e., the value of active becomes greater than 0 for first time and then incrementally gets added with one value for the next record. Any suggestions?



I am expecting the output as follows:



 name     age 
John 0
John 0
John 1
John 2
Emma 0
Emma 0
Emma 0
Emma 0
Edward 0
Edward 0
Edward 0
Edward 1






r dplyr plyr tidyr






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 '18 at 11:05









user3570187user3570187

625621




625621













  • What have you tried? Please give us an example of some strategies / code you have attempted

    – sorearm
    Nov 19 '18 at 11:07











  • Shouldn't John be 0,0,1,1?

    – snoram
    Nov 19 '18 at 11:15











  • no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

    – user3570187
    Nov 19 '18 at 11:19



















  • What have you tried? Please give us an example of some strategies / code you have attempted

    – sorearm
    Nov 19 '18 at 11:07











  • Shouldn't John be 0,0,1,1?

    – snoram
    Nov 19 '18 at 11:15











  • no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

    – user3570187
    Nov 19 '18 at 11:19

















What have you tried? Please give us an example of some strategies / code you have attempted

– sorearm
Nov 19 '18 at 11:07





What have you tried? Please give us an example of some strategies / code you have attempted

– sorearm
Nov 19 '18 at 11:07













Shouldn't John be 0,0,1,1?

– snoram
Nov 19 '18 at 11:15





Shouldn't John be 0,0,1,1?

– snoram
Nov 19 '18 at 11:15













no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

– user3570187
Nov 19 '18 at 11:19





no it is supposed to be 0,0,1,2 as the age of him will be incremented to the next value in the later period i.e. in tid 1 he is 0 , 2 he is still 0, as he became active and in 3 he gets 1 and 4 he gets 2

– user3570187
Nov 19 '18 at 11:19












2 Answers
2






active

oldest

votes


















2














Does this solve it for you?



library(dplyr)

df %>%
group_by(person) %>%
arrange(person, tid) %>%
mutate(active_dummy = if_else(lag(cumsum(active)) > 0, 1, 0, 0),
age = cumsum(active_dummy)) %>%
select(person, age)


which gives you



# A tibble: 12 x 2
# Groups: person [3]
person age
<chr> <dbl>
1 John 0.
2 John 0.
3 John 1.
4 John 2.
5 Emma 0.
6 Emma 0.
7 Emma 0.
8 Emma 0.
9 Edward 0.
10 Edward 0.
11 Edward 0.
12 Edward 1.





share|improve this answer


























  • why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

    – user3570187
    Nov 19 '18 at 11:23











  • thanks, it worked, you need to add arrange(tid) to make it more generic enough

    – user3570187
    Nov 19 '18 at 11:57











  • @user3570187 You are right! I update the answer.

    – davsjob
    Nov 19 '18 at 11:59



















0














An alternative solution that also does the job:



library(tidyverse)

age_counter = df %>%
arrange(tid) %>%
group_by(person) %>%
filter(cumsum(active) > 0) %>%
mutate(age = row_number() - 1)

df %>%
left_join(age_counter) %>%
replace_na(list(age = 0)) %>%
select(person, age)





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%2f53373281%2fadding-a-new-column-with-mutate-and-group-by%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









    2














    Does this solve it for you?



    library(dplyr)

    df %>%
    group_by(person) %>%
    arrange(person, tid) %>%
    mutate(active_dummy = if_else(lag(cumsum(active)) > 0, 1, 0, 0),
    age = cumsum(active_dummy)) %>%
    select(person, age)


    which gives you



    # A tibble: 12 x 2
    # Groups: person [3]
    person age
    <chr> <dbl>
    1 John 0.
    2 John 0.
    3 John 1.
    4 John 2.
    5 Emma 0.
    6 Emma 0.
    7 Emma 0.
    8 Emma 0.
    9 Edward 0.
    10 Edward 0.
    11 Edward 0.
    12 Edward 1.





    share|improve this answer


























    • why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

      – user3570187
      Nov 19 '18 at 11:23











    • thanks, it worked, you need to add arrange(tid) to make it more generic enough

      – user3570187
      Nov 19 '18 at 11:57











    • @user3570187 You are right! I update the answer.

      – davsjob
      Nov 19 '18 at 11:59
















    2














    Does this solve it for you?



    library(dplyr)

    df %>%
    group_by(person) %>%
    arrange(person, tid) %>%
    mutate(active_dummy = if_else(lag(cumsum(active)) > 0, 1, 0, 0),
    age = cumsum(active_dummy)) %>%
    select(person, age)


    which gives you



    # A tibble: 12 x 2
    # Groups: person [3]
    person age
    <chr> <dbl>
    1 John 0.
    2 John 0.
    3 John 1.
    4 John 2.
    5 Emma 0.
    6 Emma 0.
    7 Emma 0.
    8 Emma 0.
    9 Edward 0.
    10 Edward 0.
    11 Edward 0.
    12 Edward 1.





    share|improve this answer


























    • why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

      – user3570187
      Nov 19 '18 at 11:23











    • thanks, it worked, you need to add arrange(tid) to make it more generic enough

      – user3570187
      Nov 19 '18 at 11:57











    • @user3570187 You are right! I update the answer.

      – davsjob
      Nov 19 '18 at 11:59














    2












    2








    2







    Does this solve it for you?



    library(dplyr)

    df %>%
    group_by(person) %>%
    arrange(person, tid) %>%
    mutate(active_dummy = if_else(lag(cumsum(active)) > 0, 1, 0, 0),
    age = cumsum(active_dummy)) %>%
    select(person, age)


    which gives you



    # A tibble: 12 x 2
    # Groups: person [3]
    person age
    <chr> <dbl>
    1 John 0.
    2 John 0.
    3 John 1.
    4 John 2.
    5 Emma 0.
    6 Emma 0.
    7 Emma 0.
    8 Emma 0.
    9 Edward 0.
    10 Edward 0.
    11 Edward 0.
    12 Edward 1.





    share|improve this answer















    Does this solve it for you?



    library(dplyr)

    df %>%
    group_by(person) %>%
    arrange(person, tid) %>%
    mutate(active_dummy = if_else(lag(cumsum(active)) > 0, 1, 0, 0),
    age = cumsum(active_dummy)) %>%
    select(person, age)


    which gives you



    # A tibble: 12 x 2
    # Groups: person [3]
    person age
    <chr> <dbl>
    1 John 0.
    2 John 0.
    3 John 1.
    4 John 2.
    5 Emma 0.
    6 Emma 0.
    7 Emma 0.
    8 Emma 0.
    9 Edward 0.
    10 Edward 0.
    11 Edward 0.
    12 Edward 1.






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 19 '18 at 12:01

























    answered Nov 19 '18 at 11:16









    davsjobdavsjob

    57236




    57236













    • why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

      – user3570187
      Nov 19 '18 at 11:23











    • thanks, it worked, you need to add arrange(tid) to make it more generic enough

      – user3570187
      Nov 19 '18 at 11:57











    • @user3570187 You are right! I update the answer.

      – davsjob
      Nov 19 '18 at 11:59



















    • why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

      – user3570187
      Nov 19 '18 at 11:23











    • thanks, it worked, you need to add arrange(tid) to make it more generic enough

      – user3570187
      Nov 19 '18 at 11:57











    • @user3570187 You are right! I update the answer.

      – davsjob
      Nov 19 '18 at 11:59

















    why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

    – user3570187
    Nov 19 '18 at 11:23





    why do you have the >0,1,0,0 there? it is not generic enough, it should be 0 when the active sum =1 and then increments

    – user3570187
    Nov 19 '18 at 11:23













    thanks, it worked, you need to add arrange(tid) to make it more generic enough

    – user3570187
    Nov 19 '18 at 11:57





    thanks, it worked, you need to add arrange(tid) to make it more generic enough

    – user3570187
    Nov 19 '18 at 11:57













    @user3570187 You are right! I update the answer.

    – davsjob
    Nov 19 '18 at 11:59





    @user3570187 You are right! I update the answer.

    – davsjob
    Nov 19 '18 at 11:59













    0














    An alternative solution that also does the job:



    library(tidyverse)

    age_counter = df %>%
    arrange(tid) %>%
    group_by(person) %>%
    filter(cumsum(active) > 0) %>%
    mutate(age = row_number() - 1)

    df %>%
    left_join(age_counter) %>%
    replace_na(list(age = 0)) %>%
    select(person, age)





    share|improve this answer




























      0














      An alternative solution that also does the job:



      library(tidyverse)

      age_counter = df %>%
      arrange(tid) %>%
      group_by(person) %>%
      filter(cumsum(active) > 0) %>%
      mutate(age = row_number() - 1)

      df %>%
      left_join(age_counter) %>%
      replace_na(list(age = 0)) %>%
      select(person, age)





      share|improve this answer


























        0












        0








        0







        An alternative solution that also does the job:



        library(tidyverse)

        age_counter = df %>%
        arrange(tid) %>%
        group_by(person) %>%
        filter(cumsum(active) > 0) %>%
        mutate(age = row_number() - 1)

        df %>%
        left_join(age_counter) %>%
        replace_na(list(age = 0)) %>%
        select(person, age)





        share|improve this answer













        An alternative solution that also does the job:



        library(tidyverse)

        age_counter = df %>%
        arrange(tid) %>%
        group_by(person) %>%
        filter(cumsum(active) > 0) %>%
        mutate(age = row_number() - 1)

        df %>%
        left_join(age_counter) %>%
        replace_na(list(age = 0)) %>%
        select(person, age)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 12:25









        vectorsonvectorson

        213




        213






























            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%2f53373281%2fadding-a-new-column-with-mutate-and-group-by%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)