首页 文章

为什么dlpyr中的子集与tbl_df一起变化?

提问于
浏览
5

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

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

有人可以解释为什么会发生这种情况,或者我如何解决数据帧的问题?我需要在构建中使用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 ...

1 回答

  • 5

    这是故意的 .

    ?tbl_df

    方法:'tbl_df'实现了两个重要的基本方法:print只打印前10行,适合屏幕的列'['Never简化(drop),所以总是返回data.frame

    (重点补充)

    如果你 class(tbl_df(iris)) 你会看到它的类是"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 .

相关问题