R 确定第i个元素在向量中的位置

R 确定第i个元素在向量中的位置,r,R,我有一个向量:a也许使用表更容易: x <- table(a) x # a # 1 2 3 4 5 # 5 5 5 2 3 names(x)[x == max(x)] # [1] "1" "2" "3" which(a %in% names(x)[x == max(x)]) # [1] 1 2 3 5 6 8 10 12 13 14 15 16 17 18 20 下面是一些关于数字和字符向量的基准测试。数字数据的性能差异更为明显 样本数据 是的,第一个输出“1”“2”“3

我有一个向量:
a也许使用
表更容易:

x <- table(a)
x
# a
# 1 2 3 4 5 
# 5 5 5 2 3 
names(x)[x == max(x)]
# [1] "1" "2" "3"
which(a %in% names(x)[x == max(x)])
# [1]  1  2  3  5  6  8 10 12 13 14 15 16 17 18 20
下面是一些关于数字和字符向量的基准测试。数字数据的性能差异更为明显

样本数据


是的,第一个输出“1”“2”“3”的正是我要找的。如果你指出我没有提到我想避开表,我可以接受你的回答。但我也欢迎任何帮助,如果你有任何想法如何避免它。你所有的价值观在你的实际数据是积极的吗?范围是多少?try:
x tablate在其输出中有0时生成NA。说a@user2733997,你看到我之前的评论了吗?请努力修改你的标题。确定第i个元素在向量中的位置应该是一个字母的答案。。。
[1] 3 3 3 5 2 2 4 1 4 2 5 1 2 1 3 1 3 2 5 1
[1] 5 5 5 2 3
[1] 5
x <- table(a)
x
# a
# 1 2 3 4 5 
# 5 5 5 2 3 
names(x)[x == max(x)]
# [1] "1" "2" "3"
which(a %in% names(x)[x == max(x)])
# [1]  1  2  3  5  6  8 10 12 13 14 15 16 17 18 20
x <- tabulate(a)
sort(unique(a))[x == max(x)]
set.seed(1)
a <- sample(20, 1000000, replace = TRUE)
b <- sample(letters, 1000000, replace = TRUE)
t1 <- function() {
  x <- table(a)
  out1 <- names(x)[x == max(x)]
  out1
}

t2 <- function() {
  x <- tabulate(a)
  out2 <- sort(unique(a))[x == max(x)]
  out2
}

t3 <- function() {
  x <- table(b)
  out3 <- names(x)[x == max(x)]
  out3
}

t4 <- function() {
  x <- tabulate(factor(b))
  out4 <- sort(unique(b))[x == max(x)]
  out4
}
library(rbenchmark)
benchmark(t1(), t2(), t3(), t4(), replications =  50)
#   test replications elapsed relative user.self sys.self user.child sys.child
# 1 t1()           50  30.548   24.244    30.416    0.064          0         0
# 2 t2()           50   1.260    1.000     1.240    0.016          0         0
# 3 t3()           50   8.919    7.079     8.740    0.160          0         0
# 4 t4()           50   5.680    4.508     5.564    0.100          0         0