我正试着在Tidyquant tibble中添加一列。下面是代码:
library(tidyquant)
symbol <- 'AAPL'
start_date <- as.Date('2022-01-01')
end_date <- as.Date('2022-03-31')
prices <- tq_get(symbol,
from = start_date,
to = end_date,
get = 'stock.prices')
head(prices)
# A tibble: 6 x 8
symbol date open high low close volume adjusted
<chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 AAPL 2022-01-03 178. 183. 178. 182. 104487900 182.
2 AAPL 2022-01-04 183. 183. 179. 180. 99310400 179.
3 AAPL 2022-01-05 180. 180. 175. 175. 94537600 175.
4 AAPL 2022-01-06 173. 175. 172. 172 96904000 172.
5 AAPL 2022-01-07 173. 174. 171. 172. 86709100 172.
6 AAPL 2022-01-10 169. 172. 168. 172. 106765600 172.现在,我尝试使用以下方法添加change_on_day列(这只是一天和下一天“调整后的”价格之间的差异):
prices$change_on_day <- diff(prices$adjusted)错误信息是:
Error: Assigned data `diff(prices$adjusted)` must be compatible with existing data.
x Existing data has 61 rows.
x Assigned data has 60 rows.
i Only vectors of size 1 are recycled.我该如何添加这个价差栏?
谢谢!
发布于 2022-04-18 03:50:38
如果您试图从以前的日期值中获取今天的值,那么您应该可以使用lag()函数来实现这一点。
prices %>%
mutate(change_on_day=adjusted-lag(adjusted,1))https://stackoverflow.com/questions/71906876
复制相似问题