How to obtain a position of last non-zero element Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to trim leading and trailing whitespace?How do I replace NA values with zeros in an R dataframe?data.table vs dplyr: can one do something well the other can't or does poorly?Calculate days since last event in REfficient way of taking the max date within groupsTurn off verbose messages when loading tidyverse using library() functionColumn name of last non-NA row per row; using tidyverse solution?Filtering data relative to first and last occurance of an eventdplyr approach to get the last row number with a positive valueA code to imput missing values with linear dependency

Did John Wesley plagiarize Matthew Henry...?

Why not use the yoke to control yaw, as well as pitch and roll?

How to ask rejected full-time candidates to apply to teach individual courses?

Found this skink in my tomato plant bucket. Is he trapped? Or could he leave if he wanted?

Does a random sequence of vectors span a Hilbert space?

How could a hydrazine and N2O4 cloud (or it's reactants) show up in weather radar?

What is a more techy Technical Writer job title that isn't cutesy or confusing?

How do Java 8 default methods hеlp with lambdas?

Meaning of 境 in その日を境に

An isoperimetric-type inequality inside a cube

Did pre-Columbian Americans know the spherical shape of the Earth?

Are there any irrational/transcendental numbers for which the distribution of decimal digits is not uniform?

What was the last profitable war?

Flight departed from the gate 5 min before scheduled departure time. Refund options

Marquee sign letters

Is there a spell that can create a permanent fire?

Why does BitLocker not use RSA?

How to infer difference of population proportion between two groups when proportion is small?

What does 丫 mean? 丫是什么意思?

Does the Rock Gnome trait Artificer's Lore apply when you aren't proficient in History?

What are some likely causes to domain member PC losing contact to domain controller?

Does the universe have a fixed centre of mass?

Did any compiler fully use 80-bit floating point?

Vertical ranges of Column Plots in 12



How to obtain a position of last non-zero element



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to trim leading and trailing whitespace?How do I replace NA values with zeros in an R dataframe?data.table vs dplyr: can one do something well the other can't or does poorly?Calculate days since last event in REfficient way of taking the max date within groupsTurn off verbose messages when loading tidyverse using library() functionColumn name of last non-NA row per row; using tidyverse solution?Filtering data relative to first and last occurance of an eventdplyr approach to get the last row number with a positive valueA code to imput missing values with linear dependency



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








18















I've got a binary variable representing if event happened or not:



event <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0)


I need to obtain a variable that would indicate the time when the last event happened. The expected output would be:



last_event <- c(0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13)


How can I obtain that with base R, tidyverse or any other way?










share|improve this question




























    18















    I've got a binary variable representing if event happened or not:



    event <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0)


    I need to obtain a variable that would indicate the time when the last event happened. The expected output would be:



    last_event <- c(0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13)


    How can I obtain that with base R, tidyverse or any other way?










    share|improve this question
























      18












      18








      18


      1






      I've got a binary variable representing if event happened or not:



      event <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0)


      I need to obtain a variable that would indicate the time when the last event happened. The expected output would be:



      last_event <- c(0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13)


      How can I obtain that with base R, tidyverse or any other way?










      share|improve this question














      I've got a binary variable representing if event happened or not:



      event <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0)


      I need to obtain a variable that would indicate the time when the last event happened. The expected output would be:



      last_event <- c(0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13)


      How can I obtain that with base R, tidyverse or any other way?







      r tidyverse base






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 11 at 14:08









      jakesjakes

      486315




      486315






















          4 Answers
          4






          active

          oldest

          votes


















          18














          Taking advantage of the fact that you have a binary vector, the following gives your desired output:



          cummax(seq_along(event) * event)





          share|improve this answer


















          • 6





            Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

            – Konrad Rudolph
            Apr 11 at 14:27






          • 3





            or without multiplication cummax(ifelse(event, seq_along(event), 0))

            – jogo
            Apr 11 at 14:27











          • @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

            – Konrad Rudolph
            Apr 11 at 14:28


















          8














          Whenever you need to fill repetitions with a value, think run-length encoding.



          In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:



          lengths = rle(event == 0)$lengths
          nonzeros = which(event != 0)
          runs = c(0, rep(nonzeros, each = 2))
          result = rep(runs, lengths)


          Alternative, substitute the runs in the RLE and then inverse it:



          rle = rle(event == 0)
          nonzeros = which(event != 0)
          rle$values = c(0, rep(nonzeros, each = 2))
          result = inverse.rle(rle)





          share|improve this answer






























            1














            You can also do somthing like this-



            > zero.locf <- function(x) 
            v <- x!=0
            c(0, x[v])[cumsum(v)+1]


            > zero.locf(1:length(event)*event)

            [1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





            share|improve this answer






























              1














              Another option is to find the index where event == 1 and repeat it based on length.



              rep(c(0, which(event == 1)), tapply(event, cumsum(event == 1), length))
              #[1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





              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%2f55634527%2fhow-to-obtain-a-position-of-last-non-zero-element%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                18














                Taking advantage of the fact that you have a binary vector, the following gives your desired output:



                cummax(seq_along(event) * event)





                share|improve this answer


















                • 6





                  Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                  – Konrad Rudolph
                  Apr 11 at 14:27






                • 3





                  or without multiplication cummax(ifelse(event, seq_along(event), 0))

                  – jogo
                  Apr 11 at 14:27











                • @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                  – Konrad Rudolph
                  Apr 11 at 14:28















                18














                Taking advantage of the fact that you have a binary vector, the following gives your desired output:



                cummax(seq_along(event) * event)





                share|improve this answer


















                • 6





                  Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                  – Konrad Rudolph
                  Apr 11 at 14:27






                • 3





                  or without multiplication cummax(ifelse(event, seq_along(event), 0))

                  – jogo
                  Apr 11 at 14:27











                • @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                  – Konrad Rudolph
                  Apr 11 at 14:28













                18












                18








                18







                Taking advantage of the fact that you have a binary vector, the following gives your desired output:



                cummax(seq_along(event) * event)





                share|improve this answer













                Taking advantage of the fact that you have a binary vector, the following gives your desired output:



                cummax(seq_along(event) * event)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 11 at 14:24









                mgiormentimgiormenti

                444211




                444211







                • 6





                  Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                  – Konrad Rudolph
                  Apr 11 at 14:27






                • 3





                  or without multiplication cummax(ifelse(event, seq_along(event), 0))

                  – jogo
                  Apr 11 at 14:27











                • @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                  – Konrad Rudolph
                  Apr 11 at 14:28












                • 6





                  Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                  – Konrad Rudolph
                  Apr 11 at 14:27






                • 3





                  or without multiplication cummax(ifelse(event, seq_along(event), 0))

                  – jogo
                  Apr 11 at 14:27











                • @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                  – Konrad Rudolph
                  Apr 11 at 14:28







                6




                6





                Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                – Konrad Rudolph
                Apr 11 at 14:27





                Yes! So much more elegant than my solution. I was thinking about cumulative sums but I didn’t think of multiplying the indices by the binary vector.

                – Konrad Rudolph
                Apr 11 at 14:27




                3




                3





                or without multiplication cummax(ifelse(event, seq_along(event), 0))

                – jogo
                Apr 11 at 14:27





                or without multiplication cummax(ifelse(event, seq_along(event), 0))

                – jogo
                Apr 11 at 14:27













                @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                – Konrad Rudolph
                Apr 11 at 14:28





                @jogo That solution makes sense if the type of event is logical. It does work even for a numeric vector due to R’s implicit conversions but … eh.

                – Konrad Rudolph
                Apr 11 at 14:28













                8














                Whenever you need to fill repetitions with a value, think run-length encoding.



                In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:



                lengths = rle(event == 0)$lengths
                nonzeros = which(event != 0)
                runs = c(0, rep(nonzeros, each = 2))
                result = rep(runs, lengths)


                Alternative, substitute the runs in the RLE and then inverse it:



                rle = rle(event == 0)
                nonzeros = which(event != 0)
                rle$values = c(0, rep(nonzeros, each = 2))
                result = inverse.rle(rle)





                share|improve this answer



























                  8














                  Whenever you need to fill repetitions with a value, think run-length encoding.



                  In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:



                  lengths = rle(event == 0)$lengths
                  nonzeros = which(event != 0)
                  runs = c(0, rep(nonzeros, each = 2))
                  result = rep(runs, lengths)


                  Alternative, substitute the runs in the RLE and then inverse it:



                  rle = rle(event == 0)
                  nonzeros = which(event != 0)
                  rle$values = c(0, rep(nonzeros, each = 2))
                  result = inverse.rle(rle)





                  share|improve this answer

























                    8












                    8








                    8







                    Whenever you need to fill repetitions with a value, think run-length encoding.



                    In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:



                    lengths = rle(event == 0)$lengths
                    nonzeros = which(event != 0)
                    runs = c(0, rep(nonzeros, each = 2))
                    result = rep(runs, lengths)


                    Alternative, substitute the runs in the RLE and then inverse it:



                    rle = rle(event == 0)
                    nonzeros = which(event != 0)
                    rle$values = c(0, rep(nonzeros, each = 2))
                    result = inverse.rle(rle)





                    share|improve this answer













                    Whenever you need to fill repetitions with a value, think run-length encoding.



                    In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:



                    lengths = rle(event == 0)$lengths
                    nonzeros = which(event != 0)
                    runs = c(0, rep(nonzeros, each = 2))
                    result = rep(runs, lengths)


                    Alternative, substitute the runs in the RLE and then inverse it:



                    rle = rle(event == 0)
                    nonzeros = which(event != 0)
                    rle$values = c(0, rep(nonzeros, each = 2))
                    result = inverse.rle(rle)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Apr 11 at 14:23









                    Konrad RudolphKonrad Rudolph

                    405k1017951041




                    405k1017951041





















                        1














                        You can also do somthing like this-



                        > zero.locf <- function(x) 
                        v <- x!=0
                        c(0, x[v])[cumsum(v)+1]


                        > zero.locf(1:length(event)*event)

                        [1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                        share|improve this answer



























                          1














                          You can also do somthing like this-



                          > zero.locf <- function(x) 
                          v <- x!=0
                          c(0, x[v])[cumsum(v)+1]


                          > zero.locf(1:length(event)*event)

                          [1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                          share|improve this answer

























                            1












                            1








                            1







                            You can also do somthing like this-



                            > zero.locf <- function(x) 
                            v <- x!=0
                            c(0, x[v])[cumsum(v)+1]


                            > zero.locf(1:length(event)*event)

                            [1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                            share|improve this answer













                            You can also do somthing like this-



                            > zero.locf <- function(x) 
                            v <- x!=0
                            c(0, x[v])[cumsum(v)+1]


                            > zero.locf(1:length(event)*event)

                            [1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 11 at 14:30









                            RushabhRushabh

                            1,345322




                            1,345322





















                                1














                                Another option is to find the index where event == 1 and repeat it based on length.



                                rep(c(0, which(event == 1)), tapply(event, cumsum(event == 1), length))
                                #[1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                                share|improve this answer



























                                  1














                                  Another option is to find the index where event == 1 and repeat it based on length.



                                  rep(c(0, which(event == 1)), tapply(event, cumsum(event == 1), length))
                                  #[1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                                  share|improve this answer

























                                    1












                                    1








                                    1







                                    Another option is to find the index where event == 1 and repeat it based on length.



                                    rep(c(0, which(event == 1)), tapply(event, cumsum(event == 1), length))
                                    #[1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13





                                    share|improve this answer













                                    Another option is to find the index where event == 1 and repeat it based on length.



                                    rep(c(0, which(event == 1)), tapply(event, cumsum(event == 1), length))
                                    #[1] 0 0 0 0 5 5 5 5 5 5 5 5 13 13 13 13






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Apr 11 at 14:31









                                    Ronak ShahRonak Shah

                                    48.7k104370




                                    48.7k104370



























                                        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%2f55634527%2fhow-to-obtain-a-position-of-last-non-zero-element%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

                                        Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                                        Luettelo Yhdysvaltain laivaston lentotukialuksista Lähteet | Navigointivalikko

                                        Gary (muusikko) Sisällysluettelo Historia | Rockin' High | Lähteet | Aiheesta muualla | NavigointivalikkoInfobox OKTuomas "Gary" Keskinen Ancaran kitaristiksiProjekti Rockin' High