簡體   English   中英

如何在一個select語句中同時使用starts_with和ends_with?

[英]How to use both starts_with and ends_with at the same time in one select statement?

我想選擇所有以fy開頭並以使用dplyr giving列結束。 我嘗試了以下代碼

df %>% select(start_with('fy') & ends_with('giving')

但它不起作用。

p / s:實際上我可以使用以下塊來破解它

df %>% select(starts_with('fy')) %>% select(ends_with('giving'))

但我仍然希望將所有這兩個條件放在一個地方

您可以嘗試使用matches和正則表達式:

 df %>% select(matches("^fy.*giving$"))

應該做的工作。

使用iris的虛擬示例:

iris %>% select(matches("^Pet.*gth$")) %>% colnames
[1] "Petal.Length"

你可以用這個:

df %>% select(intersect(starts_with('fy') , ends_with('giving')))

添加了與@Vincent Bonhomme相同的例子:

iris %>% select(intersect(starts_with("Pet"), ends_with("gth"))) %>% colnames
#[1] "Petal.Length"

暫無
暫無

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

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