R中基于零的数组/向量 [英] Zero based arrays/vectors in R

查看:24
本文介绍了R中基于零的数组/向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些方法可以使R对向量和其他序列数据结构使用从零开始的索引,如下所述,例如在C和python中.

Is there some way to make R use zero based indexing for vectors and other sequence data structures as is followed, for example in C and python.

我们有一些代码可以在C语言中进行一些数值处理,我们正在考虑将其移植到R中以利用其先进的统计功能,但是(根据我对谷歌搜索后的理解)缺少基于零的索引使得任务有点困难.

We have some code that does some numerical processing in C, we are thinking of porting it over into R to make use of its advanced statistical functions, but the lack(as per my understanding after googling) of zero based index makes the task a bit more difficult.

推荐答案

TL; DR:不要这样做!

我认为从零/一开始的索引并不是将C代码移植到R的主要障碍.但是,如果您真的认为有必要这样做,则可以肯定地重写 .Primitive('[')函数,从而更改R中的索引/子集的行为.

I don't think the zero/one-based indexing is a major obstacle in porting your C code to R. However, if you truly believe that it is necessary to do so, you can certainly override the .Primitive('[') function, changing the behavior of the indexing/subsetting in R.

# rename the original `[`
> index1 <- .Primitive('[')

# WICKED!: override `[`. 
> `[` <- function(v, i) index1(v, i+1)
> x <- 1:5
> x[0]
[1] 1
> x[1]
[1] 2
> x[0:2]
[1] 1 2 3

但是,这可能会非常危险,因为您更改了基本索引行为,并且可能对所有利用子集和索引的库和函数造成意外的级联效果.

However, this can be seriously dangerous because you changed the fundamental indexing behavior and can cause unexpected cascading effects for all libraries and functions that utilizes subsetting and indexing.

例如,由于子集和索引可以接受其他类型的数据作为选择器(例如布尔矢量),并且简单的覆盖功能没有考虑到这一点,因此您可能会遇到非常奇怪的行为:

For example, because subsetting and indexing can accept other type of data as a selector (boolean vector, say), and the simple overriding function doesn't take that into account, you can have very strange behavior:

> x[x > 2] # x > 2 returns a boolean vector, and by + 1, you convert 
           # boolean FALSE/TRUE to numeric 0/1
[1] 1 1 2 2 2

尽管可以通过修改覆盖功能来解决此问题,但是您仍然可能还有其他问题.

Although this can be addressed by modifying the overriding function, you still may have other issues.

另一个例子:

> (idx <- which(x > 2)) # which() still gives you 1-based index
> x[idx]
[1]  4  5 NA

您永远不知道哪里可能出问题了.所以,只是不要.

You never know where things might go wrong horribly. So, just don't.

这篇关于R中基于零的数组/向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆