【发布时间】:2019-06-18 07:50:52
【问题描述】:
我想计算显示差距的列中数字的第一个四分位数。在本专栏中,有正数和负数,所以我想只过滤掉正数并计算四分位数(第一个),但我遇到了函数问题(见下面的代码)
#我尝试了一个带有“>0”和“0.25”的函数来获得第一个四分位数,但不知何故失败了,我不知道为什么。
library(quantmod)
Symbols <- c("FB","AAPL","AMZN","NFLX","GOOG")
getSymbols(Symbols,from="2018-06-01")
stock_data = sapply(.GlobalEnv, is.xts)
all_stocks <- do.call(list, mget(names(stock_data)[stock_data]))
# Calculate gap
Gap_function <- function(x) {
stock_name <- stringi::stri_extract(names(x)[1], regex = "^[A-Z]+")
stock_name <- paste0(stock_name, ".Gap")
column_names <- c(names(x), stock_name)
x$rgap <- quantmod::Op(x) - lag(quantmod::Cl(x))
x <- setNames(x, column_names)
return(x)
}
all_stocks <- lapply(all_stocks, Gap_function)
# Calculate 1st Quantile of positive numbers in .GAP column, currently it is not working.
# I don't know how to indicate to use only positive numbers (>0) and (1st quartile 0.25)
Quartile1_function <- function(x) {
stock_name <- stringi::stri_extract(names(x)[1], regex = "^[A-Z]+")
stock_name <- paste0(stock_name, ".GapQ1")
column_names <- c(names(x), stock_name)
x$quartile1 <- (quantile(x,na.rm=TRUE [,grep(".Gap" >0, colnames(x))], 0.25))
x <- setNames(x, column_names)
return(x)
}
all_stocks <- lapply(all_stocks, Quartile1_function)
#The desired result is to get a 1st quartile of .Gap column (taking only positive numbers) in a new column =(7.609986)
#If you run this code you will get AMZN quartiles only for positive numbers in the .Gap column. but I don't know what is failing to get a function to do this for all stocks.
quantile(all_stocks$AMZN$AMZN.Gap[which(all_stocks$AMZN$AMZN.Gap >0)])
0% 25% 50% 75% 100%
0.060059 7.609986 11.709961 21.319946 88.640015
【问题讨论】:
标签: r function quantmod quantile