【问题标题】:How to use both starts_with and ends_with at the same time in one select statement?如何在一个select语句中同时使用starts_with和ends_with?
【发布时间】:2017-04-12 05:00:09
【问题描述】:
我想使用dplyr 选择以fy 开头并以giving 结尾的所有列。我尝试了以下代码
df %>% select(start_with('fy') & ends_with('giving')
但它没有用。
p/s:实际上我可以用下面的块破解它
df %>% select(starts_with('fy')) %>% select(ends_with('giving'))
但我还是想把这两个条件放在一个地方
【问题讨论】:
标签:
r
select
dplyr
conditional-statements
【解决方案1】:
您可以尝试使用matches 来代替正则表达式:
df %>% select(matches("^fy.*giving$"))
应该做的工作。
一个使用iris的虚拟示例:
iris %>% select(matches("^Pet.*gth$")) %>% colnames
[1] "Petal.Length"
【讨论】:
-
我也不是。然后我花了一些时间来学习它的语法(感谢this),它为我节省了几周的工作时间来更好地享受现实生活,然后我变成了一个巨大的正则表达式粉丝;-)
-
【解决方案2】:
你可以用这个:
df %>% select(intersect(starts_with('fy') , ends_with('giving')))
添加了与@Vincent Bonhomme 相同的示例:
iris %>% select(intersect(starts_with("Pet"), ends_with("gth"))) %>% colnames
#[1] "Petal.Length"