Search code examples
rtime-seriestsibble

How to divide a tsibble column by a number in R?


I posted a similar question a while ago and got an anwser that worked for an xts:

standardize<-function(ts) { as.xts(apply(ts, 2, function(x) x / x[1])) }

Now I have a tsibble that fails with a:

Error in x/x[1] : non-numeric argument to binary operator


require(fpp3)
goog<-gafa_stock|>filter(Symbol=="GOOG",year(Date)==2018)
    close<-goog|>select(Close)
    close1 <- apply(close, 2, function(x) x / x[1])

Solution

  • We can do it this way. apply expects an array, including a matrix. We can use mutate with group_by() and use Close = Close / first(Close):

    require(fpp3)
    
    gafa_stock %>% 
      filter(Symbol=="GOOG", year(Date)==2018) %>% 
      #group_by(Symbol) %>% 
      mutate(Close = Close / first(Close))
    
    # A tsibble: 251 x 8 [!]
    # Key:       Symbol [1]
    # Groups:    Symbol [1]
       Symbol Date        Open  High   Low Close Adj_Close  Volume
       <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>   <dbl>
     1 GOOG   2018-01-02 1048. 1067. 1045.  1        1065  1237600
     2 GOOG   2018-01-03 1064. 1086. 1063.  1.02     1082. 1430200
     3 GOOG   2018-01-04 1088  1094. 1084.  1.02     1086. 1004600
     4 GOOG   2018-01-05 1094  1104. 1092   1.03     1102. 1279100
     5 GOOG   2018-01-08 1102. 1111. 1102.  1.04     1107. 1047600
     6 GOOG   2018-01-09 1109. 1111. 1101.  1.04     1106.  902500
     7 GOOG   2018-01-10 1097. 1105. 1096.  1.04     1103. 1042800
     8 GOOG   2018-01-11 1106. 1107. 1100.  1.04     1106.  978300
     9 GOOG   2018-01-12 1102. 1124. 1101.  1.05     1122. 1720500
    10 GOOG   2018-01-16 1133. 1140. 1118.  1.05     1122. 1575300
    # … with 241 more rows