为什么x [0]返回零长度向量? [英] why does `x[0]` return a zero-length vector?

查看:116
本文介绍了为什么x [0]返回零长度向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个向量,例如x <- 1:10,那么x[0]返回一个与x相同类别(此处为integer(0))的零长度向量.

Say I have a vector, for example, x <- 1:10, then x[0] returns a zero-length vector of the same class as x, here integer(0).

我想知道该选择背后是否有原因,而不是抛出错误或像x[11]那样返回NA?另外,如果您想到让x[0]返回integer(0)有用的情况,则感谢您将其包含在答案中.

I was wondering if there is a reason behind that choice, as opposed to throwing an error, or returning NA as x[11] would? Also, if you can think of a situation where having x[0] return integer(0) is useful, thank you for including it in your answer.

推荐答案

?"["

NA和零值是允许的:包含 零将被忽略,而包含NA的行将在 结果.

NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.

因此索引0会被忽略.我们可以在下面看到它

So an index of 0 just gets ignored. We can see this in the following

x <- 1:10
x[c(1, 3, 0, 5, 0)]
#[1] 1 3 5

因此,如果我们给它的唯一索引是0,那么适当的响应是返回一个空向量.

So if the only index we give it is 0 then the appropriate response is to return an empty vector.

这篇关于为什么x [0]返回零长度向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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