简体   繁体   English

过滤两列等于相同值的数据框

[英]Filter dataframes where two columns equal to same value

Is there a way or writing 有没有办法写

filter(dataDF, column1 == 'myvalue' & column2 == 'myvalue')

without having to write out myvalue twice? 不必两次写出myvalue

您可以使用dplyr::filter_at

filter_at(dataDF, c("column1", "column2"), all_vars(. == 'myvalue'))

By your comment, 根据您的评论,

hmm, better than what I had. 嗯,比我的好。 Reasons I want to do it is 1. Such that if I need to go and edit what 'myvalue' at a later date I only need to change it in once place and 2. To make code as efficient and short as possible. 我要这样做的原因是1.这样以后如果我需要去编辑“ myvalue”,我只需要一次更改它; 2.使代码尽可能高效和简短。 Your solution solves number 1. but not number 2 您的解决方案可以解决1号问题,但不能解决2号问题

You can put the 'myValue' in a variable and use it . 您可以将'myValue'放入变量中并使用它。 That way you only have to update/change it at one place. 这样,您只需要在一个地方进行更新/更改即可。

valueToCheck='myvalue'
filter(dataDF, column1 == valueToCheck & column2 == valueToCheck)

一种笨拙的base-R解决方案

df[do.call(`&`, lapply(df[, c('column1', 'column2')], `==`, myvalue)), ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM