filling the empty rows with zeros in R Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceRemove rows with all or some NAs (missing values) in data.frameHow do I replace NA values with zeros in an R dataframe?Create an empty data.frameAdd one row to pandas DataFrameCreating an empty Pandas DataFrame, then filling it?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasMerge multiple data.frames in R with varying row lengthFill data.frame with lists dataAdd data to data.frame with 0 rows

Blender game recording at the wrong time

Cauchy Sequence Characterized only By Directly Neighbouring Sequence Members

Cold is to Refrigerator as warm is to?

What LEGO pieces have "real-world" functionality?

Replacing HDD with SSD; what about non-APFS/APFS?

How should I respond to a player wanting to catch a sword between their hands?

Using "nakedly" instead of "with nothing on"

Active filter with series inductor and resistor - do these exist?

Typsetting diagram chases (with TikZ?)

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Simulating Exploding Dice

Two different pronunciation of "понял"

What do you call the holes in a flute?

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

What loss function to use when labels are probabilities?

How to say that you spent the night with someone, you were only sleeping and nothing else?

Classification of bundles, Postnikov towers, obstruction theory, local coefficients

Statistical model of ligand substitution

If A makes B more likely then B makes A more likely"

Mortgage adviser recommends a longer term than necessary combined with overpayments

Writing Thesis: Copying from published papers

How is simplicity better than precision and clarity in prose?

Unexpected result with right shift after bitwise negation

How does modal jazz use chord progressions?



filling the empty rows with zeros in R



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceRemove rows with all or some NAs (missing values) in data.frameHow do I replace NA values with zeros in an R dataframe?Create an empty data.frameAdd one row to pandas DataFrameCreating an empty Pandas DataFrame, then filling it?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasMerge multiple data.frames in R with varying row lengthFill data.frame with lists dataAdd data to data.frame with 0 rows



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








0















I'm using R to prepare a data.frame which will be used in mixed-effects regression later. I'm pretty new to R, I've tried to search and find the solution for my problem but I couldn't find exactly what I want.



My data.frame has 20071 rows and I want to add a new column but it has a length of 1767 and I need to fill the rest with zeros.
Here's the code:



data$M1 <- c(data$M1,(data$Mw[(data$Mw > 6.5)]-6.5))


and I'm getting this error:



Error in `$<-.data.frame`(`*tmp*`, "M1", value = c(0.0999999999999996, : 


replacement has 1767 rows, data has 20071


So I knew that I just need to add zeros of length of empty rows, but I couldn't find an answer in my search.










share|improve this question



















  • 3





    Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

    – Ronak Shah
    Mar 22 at 7:53


















0















I'm using R to prepare a data.frame which will be used in mixed-effects regression later. I'm pretty new to R, I've tried to search and find the solution for my problem but I couldn't find exactly what I want.



My data.frame has 20071 rows and I want to add a new column but it has a length of 1767 and I need to fill the rest with zeros.
Here's the code:



data$M1 <- c(data$M1,(data$Mw[(data$Mw > 6.5)]-6.5))


and I'm getting this error:



Error in `$<-.data.frame`(`*tmp*`, "M1", value = c(0.0999999999999996, : 


replacement has 1767 rows, data has 20071


So I knew that I just need to add zeros of length of empty rows, but I couldn't find an answer in my search.










share|improve this question



















  • 3





    Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

    – Ronak Shah
    Mar 22 at 7:53














0












0








0








I'm using R to prepare a data.frame which will be used in mixed-effects regression later. I'm pretty new to R, I've tried to search and find the solution for my problem but I couldn't find exactly what I want.



My data.frame has 20071 rows and I want to add a new column but it has a length of 1767 and I need to fill the rest with zeros.
Here's the code:



data$M1 <- c(data$M1,(data$Mw[(data$Mw > 6.5)]-6.5))


and I'm getting this error:



Error in `$<-.data.frame`(`*tmp*`, "M1", value = c(0.0999999999999996, : 


replacement has 1767 rows, data has 20071


So I knew that I just need to add zeros of length of empty rows, but I couldn't find an answer in my search.










share|improve this question
















I'm using R to prepare a data.frame which will be used in mixed-effects regression later. I'm pretty new to R, I've tried to search and find the solution for my problem but I couldn't find exactly what I want.



My data.frame has 20071 rows and I want to add a new column but it has a length of 1767 and I need to fill the rest with zeros.
Here's the code:



data$M1 <- c(data$M1,(data$Mw[(data$Mw > 6.5)]-6.5))


and I'm getting this error:



Error in `$<-.data.frame`(`*tmp*`, "M1", value = c(0.0999999999999996, : 


replacement has 1767 rows, data has 20071


So I knew that I just need to add zeros of length of empty rows, but I couldn't find an answer in my search.







r dataframe






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 9:00









NelsonGon

3,9714834




3,9714834










asked Mar 22 at 7:47









Oğuz Salih OkçuOğuz Salih Okçu

31




31







  • 3





    Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

    – Ronak Shah
    Mar 22 at 7:53













  • 3





    Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

    – Ronak Shah
    Mar 22 at 7:53








3




3





Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

– Ronak Shah
Mar 22 at 7:53






Do you want to just append those zeros at the end? Can you add a reproducible example with expected output ?

– Ronak Shah
Mar 22 at 7:53













5 Answers
5






active

oldest

votes


















0














You could do this:



data$M1 <- pmax(data$Mw - 6.5, 0)


The idea here is the following: You want to create a vector that contains data$Mw - 6.5 unless data$Mw < 6.5, in which case the vector should be zero. This means that you will have zero exactly when data$Mw - 6.5 < 0. So, for each i, your vector will contain the maximum of data$Mw - 6.5 and 0.



This is exactly what the function pmax() is for: it takes multiple vectors as inputs and returns the elementwise maximum. This is easiest seen with an example:



pmax(c(1, 4), c(3, 2))
[1] 3 4


The first value of the output corresponds to max(1, 3) the second value to max(4, 2).



This is considerably faster than using ifelse().






share|improve this answer
































    2














    What you are doing is extracting data that lives up to your condition (1767 rows), thus a vector that is shorter than you number of rows in your dataframe.



    You should use "ifelse" instead.



    data$M1 <- ifelse(data$Mw > 6.5,
    data$Mw - 6.5,
    0)


    If the number is above 6.5 you subtract 6.5 from the number, else you return zero.






    share|improve this answer






























      0














      This should do what you want:



      data$M1[1768:20071] <- 0


      or, if M1 is a separate vector or column of another data-frame:



      data$M1 <- c(M1, rep(0, 20071-1768))





      share|improve this answer




















      • 1





        This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

        – Rui Barradas
        Mar 22 at 8:03












      • To format code, see also here

        – Rui Barradas
        Mar 22 at 8:09


















      0














      Using cbind.fill() from the rowr library, we can bind different size dataframes/vectors while filling holes with a desired fill.



       > a=as.data.frame(matrix(0,4,2),stringsAsFactors = FALSE)
      > a
      V1 V2
      1 0 0
      2 0 0
      3 0 0
      4 0 0
      > b=c(1,2,3)

      > cbind.fill(a,b,fill=0)
      V1 V2 object
      1 0 0 1
      2 0 0 2
      3 0 0 3
      4 0 0 0





      share|improve this answer






























        0














        Another base R way is to create the column filled with zeros first and then use a logical index.



        data$M1 <- 0
        data$M1[data$Mw > 6.5] <- data$Mw[data$Mw > 6.5] - 6.5


        This is probably faster.






        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%2f55295017%2ffilling-the-empty-rows-with-zeros-in-r%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You could do this:



          data$M1 <- pmax(data$Mw - 6.5, 0)


          The idea here is the following: You want to create a vector that contains data$Mw - 6.5 unless data$Mw < 6.5, in which case the vector should be zero. This means that you will have zero exactly when data$Mw - 6.5 < 0. So, for each i, your vector will contain the maximum of data$Mw - 6.5 and 0.



          This is exactly what the function pmax() is for: it takes multiple vectors as inputs and returns the elementwise maximum. This is easiest seen with an example:



          pmax(c(1, 4), c(3, 2))
          [1] 3 4


          The first value of the output corresponds to max(1, 3) the second value to max(4, 2).



          This is considerably faster than using ifelse().






          share|improve this answer





























            0














            You could do this:



            data$M1 <- pmax(data$Mw - 6.5, 0)


            The idea here is the following: You want to create a vector that contains data$Mw - 6.5 unless data$Mw < 6.5, in which case the vector should be zero. This means that you will have zero exactly when data$Mw - 6.5 < 0. So, for each i, your vector will contain the maximum of data$Mw - 6.5 and 0.



            This is exactly what the function pmax() is for: it takes multiple vectors as inputs and returns the elementwise maximum. This is easiest seen with an example:



            pmax(c(1, 4), c(3, 2))
            [1] 3 4


            The first value of the output corresponds to max(1, 3) the second value to max(4, 2).



            This is considerably faster than using ifelse().






            share|improve this answer



























              0












              0








              0







              You could do this:



              data$M1 <- pmax(data$Mw - 6.5, 0)


              The idea here is the following: You want to create a vector that contains data$Mw - 6.5 unless data$Mw < 6.5, in which case the vector should be zero. This means that you will have zero exactly when data$Mw - 6.5 < 0. So, for each i, your vector will contain the maximum of data$Mw - 6.5 and 0.



              This is exactly what the function pmax() is for: it takes multiple vectors as inputs and returns the elementwise maximum. This is easiest seen with an example:



              pmax(c(1, 4), c(3, 2))
              [1] 3 4


              The first value of the output corresponds to max(1, 3) the second value to max(4, 2).



              This is considerably faster than using ifelse().






              share|improve this answer















              You could do this:



              data$M1 <- pmax(data$Mw - 6.5, 0)


              The idea here is the following: You want to create a vector that contains data$Mw - 6.5 unless data$Mw < 6.5, in which case the vector should be zero. This means that you will have zero exactly when data$Mw - 6.5 < 0. So, for each i, your vector will contain the maximum of data$Mw - 6.5 and 0.



              This is exactly what the function pmax() is for: it takes multiple vectors as inputs and returns the elementwise maximum. This is easiest seen with an example:



              pmax(c(1, 4), c(3, 2))
              [1] 3 4


              The first value of the output corresponds to max(1, 3) the second value to max(4, 2).



              This is considerably faster than using ifelse().







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 30 at 21:29

























              answered Mar 30 at 20:43









              StibuStibu

              10.6k43758




              10.6k43758























                  2














                  What you are doing is extracting data that lives up to your condition (1767 rows), thus a vector that is shorter than you number of rows in your dataframe.



                  You should use "ifelse" instead.



                  data$M1 <- ifelse(data$Mw > 6.5,
                  data$Mw - 6.5,
                  0)


                  If the number is above 6.5 you subtract 6.5 from the number, else you return zero.






                  share|improve this answer



























                    2














                    What you are doing is extracting data that lives up to your condition (1767 rows), thus a vector that is shorter than you number of rows in your dataframe.



                    You should use "ifelse" instead.



                    data$M1 <- ifelse(data$Mw > 6.5,
                    data$Mw - 6.5,
                    0)


                    If the number is above 6.5 you subtract 6.5 from the number, else you return zero.






                    share|improve this answer

























                      2












                      2








                      2







                      What you are doing is extracting data that lives up to your condition (1767 rows), thus a vector that is shorter than you number of rows in your dataframe.



                      You should use "ifelse" instead.



                      data$M1 <- ifelse(data$Mw > 6.5,
                      data$Mw - 6.5,
                      0)


                      If the number is above 6.5 you subtract 6.5 from the number, else you return zero.






                      share|improve this answer













                      What you are doing is extracting data that lives up to your condition (1767 rows), thus a vector that is shorter than you number of rows in your dataframe.



                      You should use "ifelse" instead.



                      data$M1 <- ifelse(data$Mw > 6.5,
                      data$Mw - 6.5,
                      0)


                      If the number is above 6.5 you subtract 6.5 from the number, else you return zero.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 22 at 8:10









                      Esben EickhardtEsben Eickhardt

                      796818




                      796818





















                          0














                          This should do what you want:



                          data$M1[1768:20071] <- 0


                          or, if M1 is a separate vector or column of another data-frame:



                          data$M1 <- c(M1, rep(0, 20071-1768))





                          share|improve this answer




















                          • 1





                            This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                            – Rui Barradas
                            Mar 22 at 8:03












                          • To format code, see also here

                            – Rui Barradas
                            Mar 22 at 8:09















                          0














                          This should do what you want:



                          data$M1[1768:20071] <- 0


                          or, if M1 is a separate vector or column of another data-frame:



                          data$M1 <- c(M1, rep(0, 20071-1768))





                          share|improve this answer




















                          • 1





                            This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                            – Rui Barradas
                            Mar 22 at 8:03












                          • To format code, see also here

                            – Rui Barradas
                            Mar 22 at 8:09













                          0












                          0








                          0







                          This should do what you want:



                          data$M1[1768:20071] <- 0


                          or, if M1 is a separate vector or column of another data-frame:



                          data$M1 <- c(M1, rep(0, 20071-1768))





                          share|improve this answer















                          This should do what you want:



                          data$M1[1768:20071] <- 0


                          or, if M1 is a separate vector or column of another data-frame:



                          data$M1 <- c(M1, rep(0, 20071-1768))






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 22 at 8:04









                          Rui Barradas

                          18.3k51833




                          18.3k51833










                          answered Mar 22 at 7:59









                          PippinéPippiné

                          122




                          122







                          • 1





                            This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                            – Rui Barradas
                            Mar 22 at 8:03












                          • To format code, see also here

                            – Rui Barradas
                            Mar 22 at 8:09












                          • 1





                            This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                            – Rui Barradas
                            Mar 22 at 8:03












                          • To format code, see also here

                            – Rui Barradas
                            Mar 22 at 8:09







                          1




                          1





                          This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                          – Rui Barradas
                          Mar 22 at 8:03






                          This answer has a problem, the OP should know beforehand the value 1768. And please learn how to format code. I did it for you since you are a new user but it's not that hard. See on top of the answer box.

                          – Rui Barradas
                          Mar 22 at 8:03














                          To format code, see also here

                          – Rui Barradas
                          Mar 22 at 8:09





                          To format code, see also here

                          – Rui Barradas
                          Mar 22 at 8:09











                          0














                          Using cbind.fill() from the rowr library, we can bind different size dataframes/vectors while filling holes with a desired fill.



                           > a=as.data.frame(matrix(0,4,2),stringsAsFactors = FALSE)
                          > a
                          V1 V2
                          1 0 0
                          2 0 0
                          3 0 0
                          4 0 0
                          > b=c(1,2,3)

                          > cbind.fill(a,b,fill=0)
                          V1 V2 object
                          1 0 0 1
                          2 0 0 2
                          3 0 0 3
                          4 0 0 0





                          share|improve this answer



























                            0














                            Using cbind.fill() from the rowr library, we can bind different size dataframes/vectors while filling holes with a desired fill.



                             > a=as.data.frame(matrix(0,4,2),stringsAsFactors = FALSE)
                            > a
                            V1 V2
                            1 0 0
                            2 0 0
                            3 0 0
                            4 0 0
                            > b=c(1,2,3)

                            > cbind.fill(a,b,fill=0)
                            V1 V2 object
                            1 0 0 1
                            2 0 0 2
                            3 0 0 3
                            4 0 0 0





                            share|improve this answer

























                              0












                              0








                              0







                              Using cbind.fill() from the rowr library, we can bind different size dataframes/vectors while filling holes with a desired fill.



                               > a=as.data.frame(matrix(0,4,2),stringsAsFactors = FALSE)
                              > a
                              V1 V2
                              1 0 0
                              2 0 0
                              3 0 0
                              4 0 0
                              > b=c(1,2,3)

                              > cbind.fill(a,b,fill=0)
                              V1 V2 object
                              1 0 0 1
                              2 0 0 2
                              3 0 0 3
                              4 0 0 0





                              share|improve this answer













                              Using cbind.fill() from the rowr library, we can bind different size dataframes/vectors while filling holes with a desired fill.



                               > a=as.data.frame(matrix(0,4,2),stringsAsFactors = FALSE)
                              > a
                              V1 V2
                              1 0 0
                              2 0 0
                              3 0 0
                              4 0 0
                              > b=c(1,2,3)

                              > cbind.fill(a,b,fill=0)
                              V1 V2 object
                              1 0 0 1
                              2 0 0 2
                              3 0 0 3
                              4 0 0 0






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 22 at 8:07









                              boskiboski

                              874418




                              874418





















                                  0














                                  Another base R way is to create the column filled with zeros first and then use a logical index.



                                  data$M1 <- 0
                                  data$M1[data$Mw > 6.5] <- data$Mw[data$Mw > 6.5] - 6.5


                                  This is probably faster.






                                  share|improve this answer



























                                    0














                                    Another base R way is to create the column filled with zeros first and then use a logical index.



                                    data$M1 <- 0
                                    data$M1[data$Mw > 6.5] <- data$Mw[data$Mw > 6.5] - 6.5


                                    This is probably faster.






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      Another base R way is to create the column filled with zeros first and then use a logical index.



                                      data$M1 <- 0
                                      data$M1[data$Mw > 6.5] <- data$Mw[data$Mw > 6.5] - 6.5


                                      This is probably faster.






                                      share|improve this answer













                                      Another base R way is to create the column filled with zeros first and then use a logical index.



                                      data$M1 <- 0
                                      data$M1[data$Mw > 6.5] <- data$Mw[data$Mw > 6.5] - 6.5


                                      This is probably faster.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 22 at 8:17









                                      Rui BarradasRui Barradas

                                      18.3k51833




                                      18.3k51833



























                                          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%2f55295017%2ffilling-the-empty-rows-with-zeros-in-r%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

                                          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현