How to obtain a position of last non-zero element The 2019 Stack Overflow Developer Survey Results Are In Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceHow 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

Do working physicists consider Newtonian mechanics to be "falsified"?

What information about me do stores get via my credit card?

Working through the single responsibility principle (SRP) in Python when calls are expensive

Is this wall load bearing? Blueprints and photos attached

Drawing vertical/oblique lines in Metrical tree (tikz-qtree, tipa)

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

How to read αἱμύλιος or when to aspirate

Python - Fishing Simulator

Didn't get enough time to take a Coding Test - what to do now?

Can withdrawing asylum be illegal?

Sort list of array linked objects by keys and values

Why not take a picture of a closer black hole?

how can a perfect fourth interval be considered either consonant or dissonant?

Make it rain characters

Why can't wing-mounted spoilers be used to steepen approaches?

First use of “packing” as in carrying a gun

Can each chord in a progression create its own key?

Can the DM override racial traits?

One-dimensional Japanese puzzle

Was credit for the black hole image misappropriated?

For what reasons would an animal species NOT cross a *horizontal* land bridge?

Huge performance difference of the command find with and without using %M option to show permissions

Did the new image of black hole confirm the general theory of relativity?

Is 'stolen' appropriate word?



How to obtain a position of last non-zero element



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceHow 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;








16















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




























    16















    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
























      16












      16








      16


      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 yesterday









      jakesjakes

      431315




      431315






















          4 Answers
          4






          active

          oldest

          votes


















          17














          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
            yesterday






          • 3





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

            – jogo
            yesterday











          • @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
            yesterday


















          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









                17














                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
                  yesterday






                • 3





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

                  – jogo
                  yesterday











                • @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
                  yesterday















                17














                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
                  yesterday






                • 3





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

                  – jogo
                  yesterday











                • @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
                  yesterday













                17












                17








                17







                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 yesterday









                mgiormentimgiormenti

                394111




                394111







                • 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
                  yesterday






                • 3





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

                  – jogo
                  yesterday











                • @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
                  yesterday












                • 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
                  yesterday






                • 3





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

                  – jogo
                  yesterday











                • @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
                  yesterday







                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
                yesterday





                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
                yesterday




                3




                3





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

                – jogo
                yesterday





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

                – jogo
                yesterday













                @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
                yesterday





                @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
                yesterday













                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 yesterday









                    Konrad RudolphKonrad Rudolph

                    404k1017921041




                    404k1017921041





















                        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 yesterday









                            RushabhRushabh

                            1,300221




                            1,300221





















                                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 yesterday









                                    Ronak ShahRonak Shah

                                    46.7k104269




                                    46.7k104269



























                                        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







                                        -base, r, tidyverse

                                        Popular posts from this blog

                                        Mobil Contents History Mobil brands Former Mobil brands Lukoil transaction Mobil UK Mobil Australia Mobil New Zealand Mobil Greece Mobil in Japan Mobil in Canada Mobil Egypt See also References External links Navigation menuwww.mobil.com"Mobil Corporation"the original"Our Houston campus""Business & Finance: Socony-Vacuum Corp.""Popular Mechanics""Lubrite Technologies""Exxon Mobil campus 'clearly happening'""Toledo Blade - Google News Archive Search""The Lion and the Moose - How 2 Executives Pulled off the Biggest Merger Ever""ExxonMobil Press Release""Lubricants""Archived copy"the original"Mobil 1™ and Mobil Super™ motor oil and synthetic motor oil - Mobil™ Motor Oils""Mobil Delvac""Mobil Industrial website""The State of Competition in Gasoline Marketing: The Effects of Refiner Operations at Retail""Mobil Travel Guide to become Forbes Travel Guide""Hotel Rankings: Forbes Merges with Mobil"the original"Jamieson oil industry history""Mobil news""Caltex pumps for control""Watchdog blocks Caltex bid""Exxon Mobil sells service station network""Mobil Oil New Zealand Limited is New Zealand's oldest oil company, with predecessor companies having first established a presence in the country in 1896""ExxonMobil subsidiaries have a business history in New Zealand stretching back more than 120 years. We are involved in petroleum refining and distribution and the marketing of fuels, lubricants and chemical products""Archived copy"the original"Exxon Mobil to Sell Its Japanese Arm for $3.9 Billion""Gas station merger will end Esso and Mobil's long run in Japan""Esso moves to affiliate itself with PC Optimum, no longer Aeroplan, in loyalty point switch""Mobil brand of gas stations to launch in Canada after deal for 213 Loblaws-owned locations""Mobil Nears Completion of Rebranding 200 Loblaw Gas Stations""Learn about ExxonMobil's operations in Egypt""Petrol and Diesel Service Stations in Egypt - Mobil"Official websiteExxon Mobil corporate websiteMobil Industrial official websiteeeeeeeeDA04275022275790-40000 0001 0860 5061n82045453134887257134887257

                                        Frič See also Navigation menuinternal link

                                        Identify plant with long narrow paired leaves and reddish stems Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?What is this plant with long sharp leaves? Is it a weed?What is this 3ft high, stalky plant, with mid sized narrow leaves?What is this young shrub with opposite ovate, crenate leaves and reddish stems?What is this plant with large broad serrated leaves?Identify this upright branching weed with long leaves and reddish stemsPlease help me identify this bulbous plant with long, broad leaves and white flowersWhat is this small annual with narrow gray/green leaves and rust colored daisy-type flowers?What is this chilli plant?Does anyone know what type of chilli plant this is?Help identify this plant