【发布时间】:2015-08-27 05:46:53
【问题描述】:
我记得 2001 年关于 r-help 的评论说 drop = TRUE in [.data.frame 是 R 历史上最糟糕的设计决策。
dplyr 更正了这一点并且不会隐式删除。当尝试将旧代码转换为dplyr 样式时,当d[, 1] 或d[1] 被假定为向量时,这会引入一些讨厌的错误。
我当前的解决方法如下所示使用unlist 来获取1 列向量。有更好的想法吗?
library(dplyr)
d2 = data.frame(x = 1:5, y = (1:5) ^ 2)
str(d2[,1]) # implicit drop = TRUE
# int [1:5] 1 2 3 4 5
str(d2[,1, drop = FALSE])
# data.frame': 5 obs. of 1 variable:
# $ x: int 1 2 3 4 5
# With dplyr functions
d1 = data_frame(x = 1:5, y = x ^ 2)
str(d1[,1])
# Classes ‘tbl_df’ and 'data.frame': 5 obs. of 1 variable:
# $ x: int 1 2 3 4 5
str(unlist(d1[,1]))
# This ugly construct gives the same as str(d2[,1])
str(d1[,1][[1]])
【问题讨论】:
-
为什么不直接使用
d1[[1]] -
也可以。在 [[]] 空间中迷路了。请张贴作为答案作为参考。我发布了这个摘要,因为我在 SO 和文档中找不到它。如果有人在
dplyr文档中发现了警告,请在此处添加链接。