You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何判断vector向量的指定索引是否存在

R语言判断指定索引是否存在于向量的实现方法

核心逻辑:R中向量的正整数合法索引范围为1:length(目标向量),仅需判断目标索引是否落在该区间内即可。

首先修正你提供的测试用例中的语法错误:small_vect<- (mode = "character", length = 10) 缺失vector构造函数,正确写法为 small_vect<- vector(mode = "character", length = 10)

1. 自定义封装函数(可复用)

# 入参:vec=目标向量,idx=待判断的正整数索引
is_index_exist <- function(vec, idx) {
  # 索引合法性校验,不需要可以删除
  if (!is.numeric(idx) || idx < 1 || idx %% 1 != 0) {
    warning("请传入正整数类型的索引")
    return(FALSE)
  }
  return(idx <= length(vec))
}

测试运行结果

# 空向量测试
empt_vect <- vector(mode = "character")
is_index_exist(empt_vect, 18)
# 输出:[1] FALSE

# 长度为100的向量测试
large_vect <- vector(mode = "character", length = 100)
is_index_exist(large_vect, 18)
# 输出:[1] TRUE

# 长度为10的向量测试
small_vect <- vector(mode = "character", length = 10)
is_index_exist(small_vect, 18)
# 输出:[1] FALSE

2. 单行判断(无需封装)

如果不需要复用,直接写逻辑语句即可:

# 示例:判断索引18是否存在于large_vect中
18 <= length(large_vect)

扩展场景:判断命名索引是否存在

如果你的向量有命名属性,需要判断某个名称的索引是否存在,使用以下语法即可:

"目标索引名" %in% names(目标向量)

内容的提问来源于stack exchange,提问作者tfr950

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:00:01