英文:
How to divide a tsibble column by a number in R?
问题
我之前发布了一个类似的问题,并得到了一个适用于xts的答案:
standardize<-function(ts) { as.xts(apply(ts, 2, function(x) x / x[1])) }
现在我有一个tsibble,在执行时出现了错误:
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])
英文:
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])
答案1
得分: 1
我们可以这样做。apply
需要一个数组,包括一个矩阵。我们可以使用 mutate
结合 group_by()
使用 Close = Close / first(Close)
:
require(fpp3)
gafa_stock %>%
filter(Symbol == "GOOG", year(Date) == 2018) %>%
#group_by(Symbol) %>%
mutate(Close = Close / first(Close))
# 一个时间序列表格: 251 x 8 [!]
# 关键词: Symbol [1]
# 分组: 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
# … 还有 241 行数据
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论