R - filling a cell with the value from the previous column





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







3















I have a dataframe like this



x <- c(1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0)
y <- c(10:20)
dat <- rbind(x, y)


I don't want the X row to contain 0s. Instead, I would like to replace the 0s with the value from the most recent non-zero column.



The expected output is



1    1    1    1    2    2    2    3    3     3     3
10 11 12 13 14 15 16 17 18 19 20


This is similar to the solution found here, but operating column-wise rather than row-wise.



Thanks!










share|improve this question





























    3















    I have a dataframe like this



    x <- c(1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0)
    y <- c(10:20)
    dat <- rbind(x, y)


    I don't want the X row to contain 0s. Instead, I would like to replace the 0s with the value from the most recent non-zero column.



    The expected output is



    1    1    1    1    2    2    2    3    3     3     3
    10 11 12 13 14 15 16 17 18 19 20


    This is similar to the solution found here, but operating column-wise rather than row-wise.



    Thanks!










    share|improve this question

























      3












      3








      3








      I have a dataframe like this



      x <- c(1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0)
      y <- c(10:20)
      dat <- rbind(x, y)


      I don't want the X row to contain 0s. Instead, I would like to replace the 0s with the value from the most recent non-zero column.



      The expected output is



      1    1    1    1    2    2    2    3    3     3     3
      10 11 12 13 14 15 16 17 18 19 20


      This is similar to the solution found here, but operating column-wise rather than row-wise.



      Thanks!










      share|improve this question














      I have a dataframe like this



      x <- c(1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0)
      y <- c(10:20)
      dat <- rbind(x, y)


      I don't want the X row to contain 0s. Instead, I would like to replace the 0s with the value from the most recent non-zero column.



      The expected output is



      1    1    1    1    2    2    2    3    3     3     3
      10 11 12 13 14 15 16 17 18 19 20


      This is similar to the solution found here, but operating column-wise rather than row-wise.



      Thanks!







      r






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 26 '18 at 16:46









      EmKayDeeEmKayDee

      413




      413
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back



          library(tidyverse)
          dat %>%
          t %>%
          as.data.frame %>%
          na_if(., 0) %>%
          fill(!!! rlang::syms(names(.))) %>%
          t





          share|improve this answer































            3














            step 1: replace all zeros with NA because, ...



            dat[1, dat[1,] == 0] <- NA


            step 2: ... you can then use a function that is esp. designed to do what you want with NA-values



            dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

            # dat[1, ] <- zoo::na.locf(dat[1, ])


            result:



            #  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
            #x 1 1 1 1 2 2 2 3 3 3 3
            #y 10 11 12 13 14 15 16 17 18 19 20




            Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.






            share|improve this answer


























            • Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

              – EmKayDee
              Nov 26 '18 at 17:31











            • Could you add data to your question that is more like your real data and where the solution fails?

              – Andre Elrico
              Nov 26 '18 at 21:32











            • @EmKayDee I have updated my solution. Please tell me if this now works for you.

              – Andre Elrico
              Nov 27 '18 at 8:50












            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%2f53485596%2fr-filling-a-cell-with-the-value-from-the-previous-column%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














            Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back



            library(tidyverse)
            dat %>%
            t %>%
            as.data.frame %>%
            na_if(., 0) %>%
            fill(!!! rlang::syms(names(.))) %>%
            t





            share|improve this answer




























              2














              Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back



              library(tidyverse)
              dat %>%
              t %>%
              as.data.frame %>%
              na_if(., 0) %>%
              fill(!!! rlang::syms(names(.))) %>%
              t





              share|improve this answer


























                2












                2








                2







                Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back



                library(tidyverse)
                dat %>%
                t %>%
                as.data.frame %>%
                na_if(., 0) %>%
                fill(!!! rlang::syms(names(.))) %>%
                t





                share|improve this answer













                Here is an option with tidyverse, where we transpose the data, and use fill on all the column, transpose it back



                library(tidyverse)
                dat %>%
                t %>%
                as.data.frame %>%
                na_if(., 0) %>%
                fill(!!! rlang::syms(names(.))) %>%
                t






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 18:12









                akrunakrun

                420k13207284




                420k13207284

























                    3














                    step 1: replace all zeros with NA because, ...



                    dat[1, dat[1,] == 0] <- NA


                    step 2: ... you can then use a function that is esp. designed to do what you want with NA-values



                    dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

                    # dat[1, ] <- zoo::na.locf(dat[1, ])


                    result:



                    #  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
                    #x 1 1 1 1 2 2 2 3 3 3 3
                    #y 10 11 12 13 14 15 16 17 18 19 20




                    Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.






                    share|improve this answer


























                    • Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                      – EmKayDee
                      Nov 26 '18 at 17:31











                    • Could you add data to your question that is more like your real data and where the solution fails?

                      – Andre Elrico
                      Nov 26 '18 at 21:32











                    • @EmKayDee I have updated my solution. Please tell me if this now works for you.

                      – Andre Elrico
                      Nov 27 '18 at 8:50
















                    3














                    step 1: replace all zeros with NA because, ...



                    dat[1, dat[1,] == 0] <- NA


                    step 2: ... you can then use a function that is esp. designed to do what you want with NA-values



                    dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

                    # dat[1, ] <- zoo::na.locf(dat[1, ])


                    result:



                    #  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
                    #x 1 1 1 1 2 2 2 3 3 3 3
                    #y 10 11 12 13 14 15 16 17 18 19 20




                    Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.






                    share|improve this answer


























                    • Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                      – EmKayDee
                      Nov 26 '18 at 17:31











                    • Could you add data to your question that is more like your real data and where the solution fails?

                      – Andre Elrico
                      Nov 26 '18 at 21:32











                    • @EmKayDee I have updated my solution. Please tell me if this now works for you.

                      – Andre Elrico
                      Nov 27 '18 at 8:50














                    3












                    3








                    3







                    step 1: replace all zeros with NA because, ...



                    dat[1, dat[1,] == 0] <- NA


                    step 2: ... you can then use a function that is esp. designed to do what you want with NA-values



                    dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

                    # dat[1, ] <- zoo::na.locf(dat[1, ])


                    result:



                    #  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
                    #x 1 1 1 1 2 2 2 3 3 3 3
                    #y 10 11 12 13 14 15 16 17 18 19 20




                    Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.






                    share|improve this answer















                    step 1: replace all zeros with NA because, ...



                    dat[1, dat[1,] == 0] <- NA


                    step 2: ... you can then use a function that is esp. designed to do what you want with NA-values



                    dat[1, ] <- zoo::na.locf(unlist(dat[1,]))

                    # dat[1, ] <- zoo::na.locf(dat[1, ])


                    result:



                    #  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
                    #x 1 1 1 1 2 2 2 3 3 3 3
                    #y 10 11 12 13 14 15 16 17 18 19 20




                    Since your example was a matrix and you possibly have a data.frame for your real data. Make sure you ?unlist your data.frame-row into a vector, so zoo::na.locf can function as desired.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 27 '18 at 8:56

























                    answered Nov 26 '18 at 16:58









                    Andre ElricoAndre Elrico

                    5,70911230




                    5,70911230













                    • Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                      – EmKayDee
                      Nov 26 '18 at 17:31











                    • Could you add data to your question that is more like your real data and where the solution fails?

                      – Andre Elrico
                      Nov 26 '18 at 21:32











                    • @EmKayDee I have updated my solution. Please tell me if this now works for you.

                      – Andre Elrico
                      Nov 27 '18 at 8:50



















                    • Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                      – EmKayDee
                      Nov 26 '18 at 17:31











                    • Could you add data to your question that is more like your real data and where the solution fails?

                      – Andre Elrico
                      Nov 26 '18 at 21:32











                    • @EmKayDee I have updated my solution. Please tell me if this now works for you.

                      – Andre Elrico
                      Nov 27 '18 at 8:50

















                    Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                    – EmKayDee
                    Nov 26 '18 at 17:31





                    Thanks! This seems like it's what I want. But when I use it on my actual dataset, I get "Error in x[[jj]][iseq] <- vjj : replacement has length zero", which I took to mean that the thing I'm trying to put in instead of an NA is empty (like I'm trying to sub an empty string in for an NA), and I'm not sure why that's the case since all the cells in that row are either a (non-empty) character string or NA. Any insight?

                    – EmKayDee
                    Nov 26 '18 at 17:31













                    Could you add data to your question that is more like your real data and where the solution fails?

                    – Andre Elrico
                    Nov 26 '18 at 21:32





                    Could you add data to your question that is more like your real data and where the solution fails?

                    – Andre Elrico
                    Nov 26 '18 at 21:32













                    @EmKayDee I have updated my solution. Please tell me if this now works for you.

                    – Andre Elrico
                    Nov 27 '18 at 8:50





                    @EmKayDee I have updated my solution. Please tell me if this now works for you.

                    – Andre Elrico
                    Nov 27 '18 at 8:50


















                    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%2f53485596%2fr-filling-a-cell-with-the-value-from-the-previous-column%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

                    Wiesbaden

                    Marschland

                    Dieringhausen