I will like to create a vector that will allow negative indexing such as -100 to 100. This means that doing G[-50] will select element at position -50 and not all element except at -50. Could you guys assist me with this. Thanks.
4 Answers
You could use a named vector
x <- 1:201
names(x) <- c(-100:100)
x["-100"]
-100
1
The indexing will be the same, but you can still access positions in the way you want if you put quotes around it

- 2,608
- 12
- 25
Numeric indices in R must be positive, so there is no way to do what you want. Here are some workarounds, though:
If you know what the minimum value is going to be (ie. indices can be from
-100
to100
) just add that number (+1
) to your indices. So instead ofdf[-100]
, you havedf[1]
You could split positive and negative indices into 2 vectors in a list. So, instead of
df[-50]
you'd usedf[[negative]][50]
.
See this example:
df <- list('pos' = c(1, 2, 3, 4, 5),
'neg' = c(-1, -2, -3, -4, -5))
neg_index <- function(df, i) {
if (i > 0) {
return(df[['pos']][i])
} else if (i < 0) {
return(df[['neg']][abs(i)])
} else {
return(NULL)
}
}
neg_index(df, -2)
[1] -2
neg_index(df, 4)
[1] 4

- 11,659
- 11
- 40
- 58
You can use a dictionary.
> library(hashmap)
> H <- hashmap(-100:100, 1:201)
> H[[-50]]
[1] 51

- 75,186
- 15
- 119
- 225
This is a weird thing to do. You can decide though to create your class to do this. Although I do not recommend you to continue doing so: I will therefore call the class weird
weird = function(x,pos = NULL){
stopifnot(length(x)%%2==1)
s = seq_along(x)
names(x) = s-floor(median(s))
class(x) = "weird"
x
}
print.weird = function(x) print(c(unname(x)))
`[.weird` = function(i,j) unname(.Primitive("[")(unclass(i),as.character(j)))
(s = weird(-10:10))
[1] -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
[19] 8 9 10
As you can see, this is just a normal vector from -10:10, the thing you cannot see is that the class of this s
is weird
. you can check by doing class(s)
Now just do:
s[-1]
[1] -1
> s[-10]
[1] -10
> s[0]
[1] 0
> s[3]
[1] 3
Also if you need to use this, then you must specify where index 0
should be. ie for example m = 1:5
what should m[0]
be? then you can change the functions accordingly

- 67,392
- 3
- 24
- 53