编写一个只能检索R中n段数据的函数

问题描述 投票:0回答:1

使用一组示例数据,如下所示:

library(quantmod)

ticker<-"AAPL"
start_date <- as.Date("2020-01-01")
end_date <- as.Date("2021-01-01")
getSymbols("AAPL", from=start_date, to=end_date)

data<-AAPL$AAPL.Adjusted

假设我只需要最后 10 或 20 列并将其放入子集中,而不是使用下面的行:

n=10

new_data<-tail(data,n=n)
    
 > new_data
           AAPL.Adjusted
2021-01-15      125.2671
2021-01-19      125.9469
2021-01-20      130.0850
2021-01-21      134.8537
2021-01-22      137.0213
2021-01-25      140.8146
2021-01-26      141.0511
2021-01-27      139.9673
2021-01-28      135.0705
2021-01-29      130.0161

是否有更好的方法从仅包含“n”句点的数据集中检索数据?谢谢。

r dataframe filter subset quantmod
1个回答
2
投票

Bubbles 正在寻找的函数是这样的:

previous_n_days<- function(d, n){
    d %>% tail(n) %>%
    head(n-1)
    }
# this assumes data goes right up until today

或者,如果需要

subset()
,则:

previous_n_days <- function(d, n){
    # check if it's in the last n days using subset
    subset(d, between(index(d), Sys.Date() - n - 1, Sys.Date() -1))
}
© www.soinside.com 2019 - 2024. All rights reserved.