为什么 dplyr 中的 tbl_df 会改变子集?

Why does subsetting change with tbl_df in dlpyr?

我在使用 dplyr tbl_df 数据帧进行子设置时发现了一些奇怪的行为。当我用 'matrix' style df[,'a'] 对数据帧进行子集时,它 returns 是预期的向量。但是,当我在 tbl_df 数据框上做同样的事情时,它 returns 是一个数据框。

我在下面使用 Iris 数据集复制了它。

有人可以解释为什么会发生这种情况,或者我如何取消 tbl_df 那个数据帧吗?我需要在需要这种行为的过程中使用 dplyr 和 readr。

library(dplyr)
data(iris)

str(iris['Sepal.Length'])
'data.frame':   150 obs. of  1 variable:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...

str(iris[,'Sepal.Length'])
 num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...

iris <- tbl_df(iris)

str(iris[,'Sepal.Length'])
Classes ‘tbl_df’ and 'data.frame':  150 obs. of  1 variable:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...

这是故意的。

参见?tbl_df

Methods:

‘tbl_df’ implements two important base methods:

print Only prints the first 10 rows, and the columns that fit on screen

‘[’ Never simplifies (drops), so always returns data.frame

(强调)

如果你class(tbl_df(iris))你会看到它的class是"tbl_df",然后是"tbl",最后是"data.frame",所以它可能有不同的[ 方法,而 methods(class='tbl_df') 确实显示 [.tbl_df.

(这有点像 data.table 包中的数据表也有不同的 [ 方法)。


编辑:取消tbl_df,只需使用data.frame,例如data.frame(tbl_df(iris)) 会将 tbl_df(..) 转换回 data.frame。