在 dplyr tbl_df 中获取删除列的最佳实践

Best practice to get a dropped column in dplyr tbl_df

我记得 2001 年对 r-help 的评论说 [.data.frame 中的 drop = TRUE 是 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]]
## [1] 1 2 3 4 5

如果你在 dplyr 中使用了很多管道,你可能还想使用 magrittr 包中的便利函数 extractextract2

d1 %>% magrittr::extract(1) %>% str
## Classes ‘tbl_df’ and 'data.frame':  5 obs. of  1 variable:
##   $ x: int  1 2 3 4 5
d1 %>% magrittr::extract2(1) %>% str
##  int [1:5] 1 2 3 4 5

或者如果 extract 对你来说太冗长,你可以直接在管道中使用 [

d1 %>% `[`(1) %>% str
## Classes ‘tbl_df’ and 'data.frame':  5 obs. of  1 variable:
##   $ x: int  1 2 3 4 5
d1 %>% `[[`(1) %>% str
##  int [1:5] 1 2 3 4 5