[R] x[0]: Can '0' be made an allowed index in R?

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sun Apr 21 10:11:19 CEST 2024


Às 09:08 de 21/04/2024, Rui Barradas escreveu:
> Às 08:55 de 21/04/2024, Hans W escreveu:
>> As we all know, in R indices for vectors start with 1, i.e, x[0] is not a
>> correct expression. Some algorithms, e.g. in graph theory or 
>> combinatorics,
>> are much easier to formulate and code if 0 is an allowed index 
>> pointing to
>> the first element of the vector.
>>
>> Some programming languages, for instance Julia (where the index for 
>> normal
>> vectors also starts with 1), provide libraries/packages that allow the 
>> user
>> to define an index range for its vectors, say 0:9 or 10:20 or even 
>> negative
>> indices.
>>
>> Of course, this notation would only be feasible for certain specially
>> defined vectors. Is there a library that provides this functionality?
>> Or is there a simple trick to do this in R? The expression 'x[0]' must
>> be possible, does this mean the syntax of R has to be twisted somehow?
>>
>> Thanks, Hans W.
>>
>>     [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> Hello,
> 
> I find what you are asking awkward but it can be done with S3 classes.
> Write an extraction method for the new class and in the use case below 
> it works. The method increments the ndex before calling NextMethod, the 
> usual extraction function.
> 
> 
> `[.zerobased` <- function(x, i, ...) {
>    i <- i + 1L
>    NextMethod()
> }
> as_zerobased <- function(x) {
>    class(x) <- c("zerobased", class(x))
>    x
> }
> 
> x <- 1:10
> y <- as_zerobased(x)
> 
> y[0]
> #> [1] 1
> y[1]
> #> [1] 2
> y[9]
> #> [1] 10
> y[10]
> #> [1] NA
> 
> 
> Hope this helps,
> 
> Rui Barradas
> 
> 
Sorry, forgot to also define a `[[zerobased` method. It's probably safer.


`[[.zerobased` <- function(x, i, ...) {
   i <- i + 1L
   NextMethod()
}


Hope this helps,

Rui Barradas


-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com



More information about the R-help mailing list