What is the point of allowing a zero index when subsetting? [closed]

浪尽此生 提交于 2019-12-23 12:16:55

问题


Since R vector indices start at 1, what is the point of allowing indexing with zero:

rivers[0]
#numeric(0)

This returns a zero length vector. Why not an error? How is this useful?


回答1:


There aren't many use cases that crop up typically. I actually have one in the context of a package I'm developing for template based validations. For example, if I want to create a template of the iris data frame, I can use:

iris[0, ]

Produces (note, showing output of str(iris[0, ])):

'data.frame': 0 obs. of  5 variables:
 $ Sepal.Length: num 
 $ Sepal.Width : num 
 $ Petal.Length: num 
 $ Petal.Width : num 
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 

I've essentially abstracted the structure of the data frame. I have all the column definitions, but none of the data.




回答2:


Because that's what the language definition specifies:

A special case is the zero index, which has null effects: x[0] is an empty vector and otherwise including zeros among positive or negative indices has the same effect as if they were omitted.



来源:https://stackoverflow.com/questions/28814918/what-is-the-point-of-allowing-a-zero-index-when-subsetting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!