How to locate the position of a specific element in an array using the R language?

In R language, you can use the which() function to find the position of a specific element in an array. Here is an example:

# 创建一个包含整数的数组
arr <- c(1, 2, 3, 4, 5)

# 查找元素为3的位置
position <- which(arr == 3)

# 打印出位置
print(position)

In the example above, we created an array called arr containing integers and used the which() function to find the position of the element 3. Finally, we printed out the result, which is the position 3.

Additionally, if there are repeated elements in the array, you can use the parameter arr.ind=TRUE in the which() function to obtain all matching index positions.示例如下:

# 创建一个包含整数的数组
arr <- c(1, 2, 3, 4, 3)

# 查找元素为3的位置
positions <- which(arr == 3, arr.ind=TRUE)

# 打印出所有位置
print(positions)
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds