问题
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