我想知道如何根据固定值显示特定范围的行:

y<-c(1,59,60,65,85,86,1550,97)
z<-c(1:8)
test<-cbind(y,z)
test

y z
[1,]    1 1
[2,]   59 2
[3,]   60 3
[4,]   65 4
[5,]   85 5
[6,]   86 6
[7,] 1550 7
[8,]   97 8

那么,碰巧我只需要看到85行中的+/-2行,有没有一种方法可以从表中提取?理想情况下,我希望有这样的东西:

enter image description here

非常感谢你的帮助.

Updated version with new function written by Peter :

#required libiaries

library(quantmod)
library(pedquant)

# download option chain from yahoo finance, using an example of ticker "BABA" & exp= "2023-06-23"
ticker<-c("BABA")
options<-getOptionChain(ticker,Exp="2023-06-23")

# seperate call/put options and display only Strike, Last Price, Volume
call_option<-options$calls[,c("Strike","Last","Vol")]
put_option<-options$puts[,c("Strike","Last","Vol")]

#getting the updated stock price to filter at-the-money level 

ticker_price<-md_stock(ticker,type="real")
price<-ticker_price$close

view_window <- function(dfr, var, x, pm){
  
  idx <- which(abs(test[, var]-x) == min(abs(test[, var] - x)))
  
  return(dfr[(idx - pm) : (idx + pm), ])
  
}

view_window(dfr=call_option,
            var=call_option$Strike,
            x=price,pm=3)

Error in test[, var] : subscript out of bounds

在本例中,数据帧[dfr]是CALL_OPTION,var是CALL_OPTION$STRING,x是交易价格,但是,显示了错误消息"Error in test[,var]:下标Out Out Bound",非常确定我的数据帧的格式有问题n函数应该工作得很好.有什么主意吗?非常感谢.

推荐答案

您可以使用如下函数:

# Where
# dfr is your data frame
# var is the quoted variable name you want to use 
# x is the value of the variable you want to centre your subset on, and 
# pm is the plus and minus range of the subset

view_window <- function(dfr, var, x, pm){

  idx <- which(abs(test[, var]-x) == min(abs(test[, var] - x)))
  
  return(dfr[(idx - pm) : (idx + pm), ])
  
}

view_window(dfr = test,
            var = "y",
            x = 85,
            pm = 2)
#>         y z
#> [1,]   60 3
#> [2,]   65 4
#> [3,]   85 5
#> [4,]   86 6
#> [5,] 1550 7

该功能的限制: 如果x在主题向量中第一个或最后一个值的正或负索引内,则函数将失败. 如果主题列中有多个等于x的值,我还没有测试效果.

创建于2023-06-21,包含reprex v2.0.2

R相关问答推荐

rvest函数read_html_live()不允许html_elements()正确读取

给定R中另一行中的值,如何插补缺失值

将一个载体的值相加,直到达到另一个载体的值

如果列中存在相同的字符串,则对行值进行总和

derrr summarise每个组返回多行?

更改默认系列1以更改名称

如何编辑ggplot的图例字使用自定义对象(gtable)?'

使用sf或terra的LINESTRAING的累积长度

提取一个列表中单个列的重复观察结果R

使用data.table::fcase()而不是dplyr::case_When()时保持值

仅 Select 超过9行的CSV文件

更新R中的数据表(使用data.table)

根据约束随机填充向量的元素

如何使用For-R循环在向量中找到一系列数字

R中Gamma回归模型均方误差的两种计算方法不一致

在R中使用列表(作为tibble列)进行向量化?

如何使用字符串从重复的模式中提取多个数字?

多元正态分布的计算

减少雨云面之间的间距并绘制所有统计数据点

如何将EC50值绘制在R中的剂量-react 曲线上?