Conditional mutate statement based on ranked order in R using dplyr::mutate() and ifelse()












2















I am trying to define the start of an interval based on the known end_time of that interval in R using dplyr::mutate() with an ifelse() statement.



I can define the start_time for the first interval easily using minimum value time value but am getting stuck with the other start times. I've tried ranking them using dense_rank(), but I do not know the proper syntax to extract the end_time for the previous ranked value. The start_time for ranked > 1 should equal the end_time + 1 for the previous ranked value.



library(dplyr)

blks <- data.frame(Group = c(rep("A", 3), rep("B", 4)),
end_time = c(4, 8, 20, 5, 11, 15, 20))

expand.grid(time = 0:20,
Group = c("A","B")) %>%
left_join(mutate(blks, time = end_time), by = c("Group", "time")) %>%
group_by(Group) %>%
mutate(ranked = dense_rank(end_time),
start_time = ifelse(ranked == 1, min(time), "WHERE I NEED HELP"))
# else = the end_time from the previous ranked + 1
# end_time[ranked == ranked-1] + 1))


Desired result is:



mutate(blks, start_time = c(0, 5, 9, 0, 6, 12, 16))  









share|improve this question


















  • 1





    blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

    – Henrik
    Dec 31 '18 at 19:16
















2















I am trying to define the start of an interval based on the known end_time of that interval in R using dplyr::mutate() with an ifelse() statement.



I can define the start_time for the first interval easily using minimum value time value but am getting stuck with the other start times. I've tried ranking them using dense_rank(), but I do not know the proper syntax to extract the end_time for the previous ranked value. The start_time for ranked > 1 should equal the end_time + 1 for the previous ranked value.



library(dplyr)

blks <- data.frame(Group = c(rep("A", 3), rep("B", 4)),
end_time = c(4, 8, 20, 5, 11, 15, 20))

expand.grid(time = 0:20,
Group = c("A","B")) %>%
left_join(mutate(blks, time = end_time), by = c("Group", "time")) %>%
group_by(Group) %>%
mutate(ranked = dense_rank(end_time),
start_time = ifelse(ranked == 1, min(time), "WHERE I NEED HELP"))
# else = the end_time from the previous ranked + 1
# end_time[ranked == ranked-1] + 1))


Desired result is:



mutate(blks, start_time = c(0, 5, 9, 0, 6, 12, 16))  









share|improve this question


















  • 1





    blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

    – Henrik
    Dec 31 '18 at 19:16














2












2








2


1






I am trying to define the start of an interval based on the known end_time of that interval in R using dplyr::mutate() with an ifelse() statement.



I can define the start_time for the first interval easily using minimum value time value but am getting stuck with the other start times. I've tried ranking them using dense_rank(), but I do not know the proper syntax to extract the end_time for the previous ranked value. The start_time for ranked > 1 should equal the end_time + 1 for the previous ranked value.



library(dplyr)

blks <- data.frame(Group = c(rep("A", 3), rep("B", 4)),
end_time = c(4, 8, 20, 5, 11, 15, 20))

expand.grid(time = 0:20,
Group = c("A","B")) %>%
left_join(mutate(blks, time = end_time), by = c("Group", "time")) %>%
group_by(Group) %>%
mutate(ranked = dense_rank(end_time),
start_time = ifelse(ranked == 1, min(time), "WHERE I NEED HELP"))
# else = the end_time from the previous ranked + 1
# end_time[ranked == ranked-1] + 1))


Desired result is:



mutate(blks, start_time = c(0, 5, 9, 0, 6, 12, 16))  









share|improve this question














I am trying to define the start of an interval based on the known end_time of that interval in R using dplyr::mutate() with an ifelse() statement.



I can define the start_time for the first interval easily using minimum value time value but am getting stuck with the other start times. I've tried ranking them using dense_rank(), but I do not know the proper syntax to extract the end_time for the previous ranked value. The start_time for ranked > 1 should equal the end_time + 1 for the previous ranked value.



library(dplyr)

blks <- data.frame(Group = c(rep("A", 3), rep("B", 4)),
end_time = c(4, 8, 20, 5, 11, 15, 20))

expand.grid(time = 0:20,
Group = c("A","B")) %>%
left_join(mutate(blks, time = end_time), by = c("Group", "time")) %>%
group_by(Group) %>%
mutate(ranked = dense_rank(end_time),
start_time = ifelse(ranked == 1, min(time), "WHERE I NEED HELP"))
# else = the end_time from the previous ranked + 1
# end_time[ranked == ranked-1] + 1))


Desired result is:



mutate(blks, start_time = c(0, 5, 9, 0, 6, 12, 16))  






r dplyr mutate






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 31 '18 at 18:39









sullijsullij

965




965








  • 1





    blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

    – Henrik
    Dec 31 '18 at 19:16














  • 1





    blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

    – Henrik
    Dec 31 '18 at 19:16








1




1





blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

– Henrik
Dec 31 '18 at 19:16





blks %>% group_by(Group) %>% mutate(start_time = c(0, head(end_time, -1) + 1))

– Henrik
Dec 31 '18 at 19:16












1 Answer
1






active

oldest

votes


















0














We can try dplyr::lag with deafult=-1 then add 1



library(dplyr)
blks %>% group_by(Group) %>% mutate(start_time = lag(end_time,default=-1)+1)

# A tibble: 7 x 3
# Groups: Group [2]
Group end_time start_time
< fct> <dbl> <dbl>
1 A 4 0
2 A 8 5
3 A 20 9
4 B 5 0
5 B 11 6
6 B 15 12
7 B 20 16





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%2f53990479%2fconditional-mutate-statement-based-on-ranked-order-in-r-using-dplyrmutate-an%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














    We can try dplyr::lag with deafult=-1 then add 1



    library(dplyr)
    blks %>% group_by(Group) %>% mutate(start_time = lag(end_time,default=-1)+1)

    # A tibble: 7 x 3
    # Groups: Group [2]
    Group end_time start_time
    < fct> <dbl> <dbl>
    1 A 4 0
    2 A 8 5
    3 A 20 9
    4 B 5 0
    5 B 11 6
    6 B 15 12
    7 B 20 16





    share|improve this answer




























      0














      We can try dplyr::lag with deafult=-1 then add 1



      library(dplyr)
      blks %>% group_by(Group) %>% mutate(start_time = lag(end_time,default=-1)+1)

      # A tibble: 7 x 3
      # Groups: Group [2]
      Group end_time start_time
      < fct> <dbl> <dbl>
      1 A 4 0
      2 A 8 5
      3 A 20 9
      4 B 5 0
      5 B 11 6
      6 B 15 12
      7 B 20 16





      share|improve this answer


























        0












        0








        0







        We can try dplyr::lag with deafult=-1 then add 1



        library(dplyr)
        blks %>% group_by(Group) %>% mutate(start_time = lag(end_time,default=-1)+1)

        # A tibble: 7 x 3
        # Groups: Group [2]
        Group end_time start_time
        < fct> <dbl> <dbl>
        1 A 4 0
        2 A 8 5
        3 A 20 9
        4 B 5 0
        5 B 11 6
        6 B 15 12
        7 B 20 16





        share|improve this answer













        We can try dplyr::lag with deafult=-1 then add 1



        library(dplyr)
        blks %>% group_by(Group) %>% mutate(start_time = lag(end_time,default=-1)+1)

        # A tibble: 7 x 3
        # Groups: Group [2]
        Group end_time start_time
        < fct> <dbl> <dbl>
        1 A 4 0
        2 A 8 5
        3 A 20 9
        4 B 5 0
        5 B 11 6
        6 B 15 12
        7 B 20 16






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 23:22









        A. SulimanA. Suliman

        5,13541122




        5,13541122
































            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%2f53990479%2fconditional-mutate-statement-based-on-ranked-order-in-r-using-dplyrmutate-an%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

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'