【发布时间】:2018-12-25 05:27:48
【问题描述】:
假设我有这个数据框:
df <- data.frame(foo = runif(10), bar = runif(10), boo = runif(10))
# bar boo foo
# 1 0.9561519 0.2152603 0.90986454
# 2 0.9971676 0.8101082 0.78158207
# 3 0.6211555 0.9281131 0.59828786
# 4 0.2332080 0.6063427 0.88131253
# 5 0.6572534 0.3698642 0.61227246
# 6 0.6940809 0.1464231 0.30366349
# 7 0.3924425 0.3706134 0.05930352
# 8 0.7918689 0.8808447 0.90571744
# 9 0.2553619 0.9632559 0.52549238
# 10 0.3772701 0.7657140 0.05102249
在选择这样的列时,我可以同时使用starts_with 和ends_with:
df %>%
select(intersect(starts_with("b"), ends_with("oo")))
正如预期的那样,这给出了以下内容:
# boo
# 1 0.2152603
# 2 0.8101082
# 3 0.9281131
# 4 0.6063427
# 5 0.3698642
# 6 0.1464231
# 7 0.3706134
# 8 0.8808447
# 9 0.9632559
# 10 0.7657140
我还可以通过否定ends_with 来选择不以oo 结尾的列,如下所示:
df %>%
select(-ends_with("oo"))
# bar
# 1 0.9561519
# 2 0.9971676
# 3 0.6211555
# 4 0.2332080
# 5 0.6572534
# 6 0.6940809
# 7 0.3924425
# 8 0.7918689
# 9 0.2553619
# 10 0.3772701
现在,我想结合这些行为。也就是说,我想要一个 not 以oo 结尾并以b 开头的列。因此,在我的示例中,我应该只获得 bar 列——但我没有。
df %>%
select(intersect(starts_with("b"), -ends_with("oo")))
# data frame with 0 columns and 10 rows
在上面,我展示了intersect 方法有效,ends_with 的否定也有效,但将这些结合起来并没有得到我期望的结果。有人能告诉我哪里出错了吗?
编辑:实际上,现在我在新的会话中重新运行它,
UseMethod("select_") 中的错误: 没有适用于“function”类对象的“select_”方法
【问题讨论】: