I have found that I can delete all rows of an R data frame by subsetting with the square bracket function and using -0 as the row index. However, I have not been able to find any documentation saying this is an official behavior that I can count on being there in the future. Is this an official function that I can use with confidence expecting that it will continue to function that way in future releases?
我发现可以通过使用方括号函数和-0作为行索引的子设置来删除R数据帧的所有行。然而,我还没有找到任何文件说这是一种官方行为,我可以指望在将来会有这种行为。这是一个正式的函数,我可以满怀信心地使用它,期待它在未来的版本中继续以这种方式运行吗?
> df <- data.frame(c1=c(1,2,3),c2=c(2,3,4), c3=c(4,5,6))
> df
c1 c2 c3
1 1 2 4
2 2 3 5
3 3 4 6
> df[-0,]
[1] c1 c2 c3
<0 rows> (or 0-length row.names)
1 个解决方案
#1
3
Let's check the documentation.
让我们检查文档。
help("[.data.frame")
says (emphasis mine):
帮助(“[.data.frame”)(强调我的)说:
When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix [...]. Note that for each selected column, xj say, typically (if it is not matrix-like), the resulting column will be xj[i], and hence rely on the corresponding [ method, see the examples section.
当[and]与两个指标(x[i, j]和x[i, j]])一起使用时,它们就像一个矩阵[…]。注意,对于每个选定的列,xj表示(如果不是类似矩阵的),结果列将是xj[i],因此依赖于相应的[方法,请参阅示例部分。
Next stop is help("[")
, which doesn't say anything about using 0 as an index, but points to the ‘R Language Definition’ manual.
下一站是help("["),它并没有提到使用0作为索引,而是指向“R语言定义”手册。
There we read (emphasis mine):
在那里我们读(强调我的):
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.
一种特殊的情况是零指标,它具有零效应:x[0]是一个空向量,否则包括正指标和负指标之间的零,其效果与被忽略的效果相同。
In summary:
总而言之:
Since this behavior is documented, you can rely on DF[0,]
returning a data.frame with empty column vectors.
由于这种行为是有文档记录的,所以您可以依赖DF[0,]返回一个带有空列向量的数据。
#1
3
Let's check the documentation.
让我们检查文档。
help("[.data.frame")
says (emphasis mine):
帮助(“[.data.frame”)(强调我的)说:
When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix [...]. Note that for each selected column, xj say, typically (if it is not matrix-like), the resulting column will be xj[i], and hence rely on the corresponding [ method, see the examples section.
当[and]与两个指标(x[i, j]和x[i, j]])一起使用时,它们就像一个矩阵[…]。注意,对于每个选定的列,xj表示(如果不是类似矩阵的),结果列将是xj[i],因此依赖于相应的[方法,请参阅示例部分。
Next stop is help("[")
, which doesn't say anything about using 0 as an index, but points to the ‘R Language Definition’ manual.
下一站是help("["),它并没有提到使用0作为索引,而是指向“R语言定义”手册。
There we read (emphasis mine):
在那里我们读(强调我的):
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.
一种特殊的情况是零指标,它具有零效应:x[0]是一个空向量,否则包括正指标和负指标之间的零,其效果与被忽略的效果相同。
In summary:
总而言之:
Since this behavior is documented, you can rely on DF[0,]
returning a data.frame with empty column vectors.
由于这种行为是有文档记录的,所以您可以依赖DF[0,]返回一个带有空列向量的数据。