簡體   English   中英

在dplyr中選擇時,使用negated ends_with和starts_with

[英]Using negated ends_with together with starts_with when selecting in dplyr

說我有這個數據框:

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_withends_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

現在,我想結合這些行為。 也就是說,我想要一個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_”)中的錯誤:沒有適用於“select_”的方法應用於類“function”的對象

使用setdiff

df %>% 
  select(setdiff(starts_with("b"), ends_with("oo")))

# bar
# 1  0.5248344
# 2  0.8835366
# 3  0.3486265
# 4  0.6382468
# 5  0.7378287
# 6  0.2878244
# 7  0.1927559
# 8  0.9787019
# 9  0.5393251
# 10 0.9229542

否定符號是由select理解的魔法,它不被intersect理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM