Difference in outputs using cumsumWhat are the differences between “=” and “<-” in R?What is the difference between require() and library()?ggplot2 and cumsum()Error in cumsum of ggplotcumsum by groupR cumunique like cumsumCumsum ignoring NA's with resetCumsum table with missing valueCumsum table with groupingCumsum excluding current value

Why did Varys remove his rings?

Why can't I share a one use code with anyone else?

UUID type for NEWID()

Single word that parallels "Recent" when discussing the near future

Can my American children re-enter the USA by International flight with a passport card? Being that their passport book has expired

Should I communicate in my applications that I'm unemployed out of choice rather than because nobody will have me?

Meaning of "legitimate" in Carl Jung's quote "Neurosis is always a substitute for legitimate suffering."

What do you call the hair or body hair you trim off your body?

Why when I add jam to my tea it stops producing thin "membrane" on top?

Why did the UK remove the 'European Union' from its passport?

Why commonly or frequently used fonts sizes are even numbers like 10px, 12px, 16px, 24px, or 32px?

2 parabolas through 4 points

Why did the soldiers of the North disobey Jon?

Developers demotivated due to working on same project for more than 2 years

What was Varys trying to do at the beginning of S08E05?

Does the Rogue's Reliable Talent feature work for thieves' tools, since the rogue is proficient in them?

tikz drawing rectangle discretized with triangle lattices and its centroids

With today's technology, could iron be smelted at La Rinconada?

In season 17 does LoN buff work against season journey set rewards?

Was the dragon prowess intentionally downplayed in S08E04?

God-Pharaoh's Statue and Finale Of Promise

Polynomial division: Is this trick obvious?

Do crew rest seats count towards the maximum allowed number of seats per flight attendant?

Why doesn't Iron Man's action affect this person in Endgame?



Difference in outputs using cumsum


What are the differences between “=” and “<-” in R?What is the difference between require() and library()?ggplot2 and cumsum()Error in cumsum of ggplotcumsum by groupR cumunique like cumsumCumsum ignoring NA's with resetCumsum table with missing valueCumsum table with groupingCumsum excluding current value






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








7















Why are these two operations different?



library(lubridate)
library(magrittr)

> seconds_to_period(1:1000) %>% cumsum %>% sum
[1] 14492440
> 1:1000 %>% cumsum %>% sum
[1] 167167000


I have seen, however, that the issue lies on the fact that cumsum only adds the seconds of the period and ignores the rest:



seconds_to_period(60) + seconds_to_period(60)
[1] "2M 0S"


but



> cumsum(c(seconds_to_period(60), seconds_to_period(60)))
[1] 0 0


Why is this behavior the default form? I think it is rather unintuitive. Additionally, what is the way to overcome this and get as a result the same as cumsum(1:1000) using 'Period' classes of lubridate that doesn't involve doing something like:



c(seconds_to_period(60), seconds_to_period(60)) %>% as.numeric %>% cumsum










share|improve this question




























    7















    Why are these two operations different?



    library(lubridate)
    library(magrittr)

    > seconds_to_period(1:1000) %>% cumsum %>% sum
    [1] 14492440
    > 1:1000 %>% cumsum %>% sum
    [1] 167167000


    I have seen, however, that the issue lies on the fact that cumsum only adds the seconds of the period and ignores the rest:



    seconds_to_period(60) + seconds_to_period(60)
    [1] "2M 0S"


    but



    > cumsum(c(seconds_to_period(60), seconds_to_period(60)))
    [1] 0 0


    Why is this behavior the default form? I think it is rather unintuitive. Additionally, what is the way to overcome this and get as a result the same as cumsum(1:1000) using 'Period' classes of lubridate that doesn't involve doing something like:



    c(seconds_to_period(60), seconds_to_period(60)) %>% as.numeric %>% cumsum










    share|improve this question
























      7












      7








      7


      1






      Why are these two operations different?



      library(lubridate)
      library(magrittr)

      > seconds_to_period(1:1000) %>% cumsum %>% sum
      [1] 14492440
      > 1:1000 %>% cumsum %>% sum
      [1] 167167000


      I have seen, however, that the issue lies on the fact that cumsum only adds the seconds of the period and ignores the rest:



      seconds_to_period(60) + seconds_to_period(60)
      [1] "2M 0S"


      but



      > cumsum(c(seconds_to_period(60), seconds_to_period(60)))
      [1] 0 0


      Why is this behavior the default form? I think it is rather unintuitive. Additionally, what is the way to overcome this and get as a result the same as cumsum(1:1000) using 'Period' classes of lubridate that doesn't involve doing something like:



      c(seconds_to_period(60), seconds_to_period(60)) %>% as.numeric %>% cumsum










      share|improve this question














      Why are these two operations different?



      library(lubridate)
      library(magrittr)

      > seconds_to_period(1:1000) %>% cumsum %>% sum
      [1] 14492440
      > 1:1000 %>% cumsum %>% sum
      [1] 167167000


      I have seen, however, that the issue lies on the fact that cumsum only adds the seconds of the period and ignores the rest:



      seconds_to_period(60) + seconds_to_period(60)
      [1] "2M 0S"


      but



      > cumsum(c(seconds_to_period(60), seconds_to_period(60)))
      [1] 0 0


      Why is this behavior the default form? I think it is rather unintuitive. Additionally, what is the way to overcome this and get as a result the same as cumsum(1:1000) using 'Period' classes of lubridate that doesn't involve doing something like:



      c(seconds_to_period(60), seconds_to_period(60)) %>% as.numeric %>% cumsum







      r lubridate cumsum






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 23 at 15:16









      FustinchoFustincho

      30719




      30719






















          1 Answer
          1






          active

          oldest

          votes


















          6














          Being cumsuma primitive, you can see here https://github.com/Microsoft/microsoft-r-open/blob/master/source/src/main/cum.c what R it is doing under the hood. Moreover, if you read from line 215:



          PROTECT(t = coerceVector(CAR(args), REALSXP));
          n = XLENGTH(t);
          PROTECT(s = allocVector(REALSXP, n));
          setAttrib(s, R_NamesSymbol, getAttrib(t, R_NamesSymbol));
          UNPROTECT(2);


          This it is doing the coercion from period to numeric and because the structure of period, it is only keeping .Data



          Compare



          seconds_to_period(60)@.Data
          seconds_to_period(59)@.Data


          Therefore, at C level, R is not doing as.numeric but a faster, more efficient (but you may say less subtle because it is not realizing others elements from .Data as as.numericdoes) coercion of data.



          Look as this:



           setClass("Foo", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar <- new("Foo",.Data=5, number1 = 12, number2 = 31)

          cumsum(bar)


          The result is 5, because it is only coercing to numeric Data



          Moreover:



           setClass("Foo2", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar2 <- new("Foo2", number1 = 12, number2 = 31)

          cumsum(bar2)


          Give you back numeric(0) because there is no .Data



          And



           setClass("Foo3", representation( number1 = "numeric", number2 = "numeric"))

          bar3 <- new("Foo3", number1 = 12, number2 = 31)

          cumsum(bar3)


          This is not working at all: without .Data, internally, R does not know how to coerce it to numeric when doing cumsum



          So: it is because of how R internally works with complex S4 objects.
          You can always tell the lubridate people to create a new parameter seconds and store in .Data the cumulative seconds of the whole S4 object. I guess this way cumsum will work. But right now, the are using .Data to store the second argument. See edit(seconds_to_period):



          function (x) 

          span <- as.double(x)
          remainder <- abs(span)
          newper <- period(second = rep(0, length(x)))
          slot(newper, "day") <- remainder%/%(3600 * 24)
          remainder <- remainder%%(3600 * 24)
          slot(newper, "hour") <- remainder%/%(3600)
          remainder <- remainder%%(3600)
          slot(newper, "minute") <- remainder%/%(60)
          slot(newper, ".Data") <- remainder%%(60)
          newper * sign(span)



          Finally, just for fun. This is my mock version of how to make cumsum work here:



          setClass("Period2",representation(.Data="numeric", period="Period"))


          seconds_to_period_2 <- function(x)
          (lapply(x, function(y) new("Period2", .Data=y, period=seconds_to_period(y))))


          a<-seconds_to_period_2(1:60)

          cumsum(a)


          Best!






          share|improve this answer




















          • 2





            I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

            – Fustincho
            Mar 24 at 7:30











          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%2f55315211%2fdifference-in-outputs-using-cumsum%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          6














          Being cumsuma primitive, you can see here https://github.com/Microsoft/microsoft-r-open/blob/master/source/src/main/cum.c what R it is doing under the hood. Moreover, if you read from line 215:



          PROTECT(t = coerceVector(CAR(args), REALSXP));
          n = XLENGTH(t);
          PROTECT(s = allocVector(REALSXP, n));
          setAttrib(s, R_NamesSymbol, getAttrib(t, R_NamesSymbol));
          UNPROTECT(2);


          This it is doing the coercion from period to numeric and because the structure of period, it is only keeping .Data



          Compare



          seconds_to_period(60)@.Data
          seconds_to_period(59)@.Data


          Therefore, at C level, R is not doing as.numeric but a faster, more efficient (but you may say less subtle because it is not realizing others elements from .Data as as.numericdoes) coercion of data.



          Look as this:



           setClass("Foo", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar <- new("Foo",.Data=5, number1 = 12, number2 = 31)

          cumsum(bar)


          The result is 5, because it is only coercing to numeric Data



          Moreover:



           setClass("Foo2", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar2 <- new("Foo2", number1 = 12, number2 = 31)

          cumsum(bar2)


          Give you back numeric(0) because there is no .Data



          And



           setClass("Foo3", representation( number1 = "numeric", number2 = "numeric"))

          bar3 <- new("Foo3", number1 = 12, number2 = 31)

          cumsum(bar3)


          This is not working at all: without .Data, internally, R does not know how to coerce it to numeric when doing cumsum



          So: it is because of how R internally works with complex S4 objects.
          You can always tell the lubridate people to create a new parameter seconds and store in .Data the cumulative seconds of the whole S4 object. I guess this way cumsum will work. But right now, the are using .Data to store the second argument. See edit(seconds_to_period):



          function (x) 

          span <- as.double(x)
          remainder <- abs(span)
          newper <- period(second = rep(0, length(x)))
          slot(newper, "day") <- remainder%/%(3600 * 24)
          remainder <- remainder%%(3600 * 24)
          slot(newper, "hour") <- remainder%/%(3600)
          remainder <- remainder%%(3600)
          slot(newper, "minute") <- remainder%/%(60)
          slot(newper, ".Data") <- remainder%%(60)
          newper * sign(span)



          Finally, just for fun. This is my mock version of how to make cumsum work here:



          setClass("Period2",representation(.Data="numeric", period="Period"))


          seconds_to_period_2 <- function(x)
          (lapply(x, function(y) new("Period2", .Data=y, period=seconds_to_period(y))))


          a<-seconds_to_period_2(1:60)

          cumsum(a)


          Best!






          share|improve this answer




















          • 2





            I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

            – Fustincho
            Mar 24 at 7:30















          6














          Being cumsuma primitive, you can see here https://github.com/Microsoft/microsoft-r-open/blob/master/source/src/main/cum.c what R it is doing under the hood. Moreover, if you read from line 215:



          PROTECT(t = coerceVector(CAR(args), REALSXP));
          n = XLENGTH(t);
          PROTECT(s = allocVector(REALSXP, n));
          setAttrib(s, R_NamesSymbol, getAttrib(t, R_NamesSymbol));
          UNPROTECT(2);


          This it is doing the coercion from period to numeric and because the structure of period, it is only keeping .Data



          Compare



          seconds_to_period(60)@.Data
          seconds_to_period(59)@.Data


          Therefore, at C level, R is not doing as.numeric but a faster, more efficient (but you may say less subtle because it is not realizing others elements from .Data as as.numericdoes) coercion of data.



          Look as this:



           setClass("Foo", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar <- new("Foo",.Data=5, number1 = 12, number2 = 31)

          cumsum(bar)


          The result is 5, because it is only coercing to numeric Data



          Moreover:



           setClass("Foo2", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar2 <- new("Foo2", number1 = 12, number2 = 31)

          cumsum(bar2)


          Give you back numeric(0) because there is no .Data



          And



           setClass("Foo3", representation( number1 = "numeric", number2 = "numeric"))

          bar3 <- new("Foo3", number1 = 12, number2 = 31)

          cumsum(bar3)


          This is not working at all: without .Data, internally, R does not know how to coerce it to numeric when doing cumsum



          So: it is because of how R internally works with complex S4 objects.
          You can always tell the lubridate people to create a new parameter seconds and store in .Data the cumulative seconds of the whole S4 object. I guess this way cumsum will work. But right now, the are using .Data to store the second argument. See edit(seconds_to_period):



          function (x) 

          span <- as.double(x)
          remainder <- abs(span)
          newper <- period(second = rep(0, length(x)))
          slot(newper, "day") <- remainder%/%(3600 * 24)
          remainder <- remainder%%(3600 * 24)
          slot(newper, "hour") <- remainder%/%(3600)
          remainder <- remainder%%(3600)
          slot(newper, "minute") <- remainder%/%(60)
          slot(newper, ".Data") <- remainder%%(60)
          newper * sign(span)



          Finally, just for fun. This is my mock version of how to make cumsum work here:



          setClass("Period2",representation(.Data="numeric", period="Period"))


          seconds_to_period_2 <- function(x)
          (lapply(x, function(y) new("Period2", .Data=y, period=seconds_to_period(y))))


          a<-seconds_to_period_2(1:60)

          cumsum(a)


          Best!






          share|improve this answer




















          • 2





            I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

            – Fustincho
            Mar 24 at 7:30













          6












          6








          6







          Being cumsuma primitive, you can see here https://github.com/Microsoft/microsoft-r-open/blob/master/source/src/main/cum.c what R it is doing under the hood. Moreover, if you read from line 215:



          PROTECT(t = coerceVector(CAR(args), REALSXP));
          n = XLENGTH(t);
          PROTECT(s = allocVector(REALSXP, n));
          setAttrib(s, R_NamesSymbol, getAttrib(t, R_NamesSymbol));
          UNPROTECT(2);


          This it is doing the coercion from period to numeric and because the structure of period, it is only keeping .Data



          Compare



          seconds_to_period(60)@.Data
          seconds_to_period(59)@.Data


          Therefore, at C level, R is not doing as.numeric but a faster, more efficient (but you may say less subtle because it is not realizing others elements from .Data as as.numericdoes) coercion of data.



          Look as this:



           setClass("Foo", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar <- new("Foo",.Data=5, number1 = 12, number2 = 31)

          cumsum(bar)


          The result is 5, because it is only coercing to numeric Data



          Moreover:



           setClass("Foo2", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar2 <- new("Foo2", number1 = 12, number2 = 31)

          cumsum(bar2)


          Give you back numeric(0) because there is no .Data



          And



           setClass("Foo3", representation( number1 = "numeric", number2 = "numeric"))

          bar3 <- new("Foo3", number1 = 12, number2 = 31)

          cumsum(bar3)


          This is not working at all: without .Data, internally, R does not know how to coerce it to numeric when doing cumsum



          So: it is because of how R internally works with complex S4 objects.
          You can always tell the lubridate people to create a new parameter seconds and store in .Data the cumulative seconds of the whole S4 object. I guess this way cumsum will work. But right now, the are using .Data to store the second argument. See edit(seconds_to_period):



          function (x) 

          span <- as.double(x)
          remainder <- abs(span)
          newper <- period(second = rep(0, length(x)))
          slot(newper, "day") <- remainder%/%(3600 * 24)
          remainder <- remainder%%(3600 * 24)
          slot(newper, "hour") <- remainder%/%(3600)
          remainder <- remainder%%(3600)
          slot(newper, "minute") <- remainder%/%(60)
          slot(newper, ".Data") <- remainder%%(60)
          newper * sign(span)



          Finally, just for fun. This is my mock version of how to make cumsum work here:



          setClass("Period2",representation(.Data="numeric", period="Period"))


          seconds_to_period_2 <- function(x)
          (lapply(x, function(y) new("Period2", .Data=y, period=seconds_to_period(y))))


          a<-seconds_to_period_2(1:60)

          cumsum(a)


          Best!






          share|improve this answer















          Being cumsuma primitive, you can see here https://github.com/Microsoft/microsoft-r-open/blob/master/source/src/main/cum.c what R it is doing under the hood. Moreover, if you read from line 215:



          PROTECT(t = coerceVector(CAR(args), REALSXP));
          n = XLENGTH(t);
          PROTECT(s = allocVector(REALSXP, n));
          setAttrib(s, R_NamesSymbol, getAttrib(t, R_NamesSymbol));
          UNPROTECT(2);


          This it is doing the coercion from period to numeric and because the structure of period, it is only keeping .Data



          Compare



          seconds_to_period(60)@.Data
          seconds_to_period(59)@.Data


          Therefore, at C level, R is not doing as.numeric but a faster, more efficient (but you may say less subtle because it is not realizing others elements from .Data as as.numericdoes) coercion of data.



          Look as this:



           setClass("Foo", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar <- new("Foo",.Data=5, number1 = 12, number2 = 31)

          cumsum(bar)


          The result is 5, because it is only coercing to numeric Data



          Moreover:



           setClass("Foo2", representation(.Data="numeric", number1 = "numeric", number2 = "numeric"))

          bar2 <- new("Foo2", number1 = 12, number2 = 31)

          cumsum(bar2)


          Give you back numeric(0) because there is no .Data



          And



           setClass("Foo3", representation( number1 = "numeric", number2 = "numeric"))

          bar3 <- new("Foo3", number1 = 12, number2 = 31)

          cumsum(bar3)


          This is not working at all: without .Data, internally, R does not know how to coerce it to numeric when doing cumsum



          So: it is because of how R internally works with complex S4 objects.
          You can always tell the lubridate people to create a new parameter seconds and store in .Data the cumulative seconds of the whole S4 object. I guess this way cumsum will work. But right now, the are using .Data to store the second argument. See edit(seconds_to_period):



          function (x) 

          span <- as.double(x)
          remainder <- abs(span)
          newper <- period(second = rep(0, length(x)))
          slot(newper, "day") <- remainder%/%(3600 * 24)
          remainder <- remainder%%(3600 * 24)
          slot(newper, "hour") <- remainder%/%(3600)
          remainder <- remainder%%(3600)
          slot(newper, "minute") <- remainder%/%(60)
          slot(newper, ".Data") <- remainder%%(60)
          newper * sign(span)



          Finally, just for fun. This is my mock version of how to make cumsum work here:



          setClass("Period2",representation(.Data="numeric", period="Period"))


          seconds_to_period_2 <- function(x)
          (lapply(x, function(y) new("Period2", .Data=y, period=seconds_to_period(y))))


          a<-seconds_to_period_2(1:60)

          cumsum(a)


          Best!







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 17:22

























          answered Mar 23 at 16:40









          LocoGrisLocoGris

          2,83821028




          2,83821028







          • 2





            I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

            – Fustincho
            Mar 24 at 7:30












          • 2





            I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

            – Fustincho
            Mar 24 at 7:30







          2




          2





          I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

          – Fustincho
          Mar 24 at 7:30





          I'm really proud of this community and answers like this one. I learned a lot with it, thank you!

          – Fustincho
          Mar 24 at 7:30



















          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%2f55315211%2fdifference-in-outputs-using-cumsum%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권, 지리지 충청도 공주목 은진현