在 R 中对数据帧进行子集化 - 意外结果

subsetting a dataframe in R - unexpected results

好的,找不到更好的标题

假设我有 my_dataframe:

Name Value1 Value2
AA    10     20
BB    15     30

如果我这样做: nrow(my_dataframe[my_dataframe$Value2>20,] 结果我得到“1”

我想创建 my_second_dataframe,例如只有 'Value2' 列:

my_second_dataframe<- my_dataframe[,'Value2', drop=FALSE]

让我看看:

class(my_second_dataframe)
[1] "data.frame"
class(my_second_dataframe$Value2)
[1] "numeric"

然后:

nrow(my_second_dataframe[my_second_dataframe$Value2>20,]
NULL

?????? 这将是一个函数的一部分,我想在其中隔离一个选择列,并根据阈值数获取该列的行数。我做错了什么?

谢谢

基于 ?Extract

中的文档

drop : For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.

此外,默认情况下它是 drop = TRUE for [

x[i, j, ... , drop = TRUE]

因此,我们需要指定 drop = FALSE 以避免在只有一列或一行时强制到尽可能低的维度。

在 OP 的示例中

my_second_dataframe[my_second_dataframe$Value2>20,, drop=FALSE]