我记得 2001 年 r-help 上的一条评论说drop = TRUE
in [.data.frame
是 R 历史上最糟糕的设计决策。
dplyr
纠正这一点并且不会隐式删除。当尝试将旧代码转换为dplyr
风格,这会引入一些讨厌的错误d[, 1]
or 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 中使用大量管道,您可能还想使用便利功能extract
and extract2
来自magrittr
包裹:
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
Or if 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)