Reputation: 2283
I have the following a
:
> a
[1] 0.32142857 0.21428571 0.10714286 0.46428571 0.42857143 0.57142857 0.35714286 0.50000000 0.67857143 0.07142857 0.92857143 0.60714286
[13] 0.17857143 0.25000000 1.00000000 0.71428571 0.64285714 0.78571429 0.57142857 0.28571429 0.57142857 0.39285714 0.96428571 0.85714286
[25] 0.75000000 0.53571429 0.82142857 0.14285714 0.39285714 0.21428571 0.03571429 0.89285714
> str (a)
num [1:32] 0.321 0.214 0.107 0.464 0.429 ...
> class (a)
[1] "numeric"
I would like to find the index value for specific element. When I use it for integer it works, but not for the others:
> which (a==1)
[1] 15
> which (a==0.10714286)
integer(0)
> match (0.10714286,a)
[1] NA
How can I get the index value 3
for 0.10714286
?
Upvotes: 0
Views: 77
Reputation: 1544
You'll have to search for the nearest value instead:
val <- 0.10714286
idx <- which.min(abs(a - val))
Upvotes: 3
Reputation: 3221
Simply use the vector to store the data. Kindly go through the following code:
> a=c(0.32142857,0.21428571,0.10714286,0.46428571,0.42857143)
> str(a)
num [1:5] 0.321 0.214 0.107 0.464 0.429
> a[1]
[1] 0.3214286
> a[2]
[1] 0.2142857
> a[3]
[1] 0.1071429
> a[4]
[1] 0.4642857
> which(a==0.10714286)
[1] 3
> class(a)
[1] "numeric"
> match(0.10714286,a)
[1] 3
Hope it works for you.
Upvotes: 0