跳到主要内容

R语言程序:查找向量中元素的索引

示例1:使用match()查找R向量元素的索引值

# 创建两个字符串
vowel_letters <- c("a", "e", "i", "o", "u")

# 查找 "i" 的索引值
match("i", vowel_letters) # 3

# 查找 "u" 的索引值
match("u", vowel_letters) # 5

输出

[1] 3
[1] 5

在上面的示例中,我们使用match()函数来查找向量vowel_letters中元素的索引。

这里:

  1. "i" 存在于 vowel_letters 中的第3个索引处,所以该方法返回3
  2. "u" 存在于 vowel_letters 中的第5个索引处,所以该方法返回5

示例2:使用which()查找R向量元素的索引值

# 创建两个字符串
languages <- c("R", "Swift", "Java", "Python")

# 使用which()查找 "Swift" 的索引值
which(languages == "Swift") # 2

# 使用which()查找 "Python" 的索引值
which(languages == "Python") # 4

输出

[1] 2
[2] 4

在这里,我们使用which()函数来查找元素的索引值。

因为:

  1. "Swift" 存在于 languages 中的第2个索引处,所以该方法返回2
  2. "Python" 存在于 languages 中的第4个索引处,所以该方法返回4