比较多列与平等
这可能是一个非常基本的问题,使用 dplyr 和 tidyverse工具,但我无法 找到一个很好的方法。
假设我具有广泛格式的数据框架,我想选择行,以便列的子集具有所有相同的值。天真的,我可以做以下操作:
> df <- tribble(
~name, ~id, ~cost, ~value1 , ~value2, ~value3,
"a", 1, 10, 1, 1, 1,
"a", 2, 20, 1, 2, 1,
"b", 3, 50, 1, 1, 3,
"b", 4, 45, 1, 1, 1,
"b", 5, 70, 2, 2, 2
)
> df %>% select(
value1 == value2 &
value1 == value3 &
value2 == value
)
# A tibble: 3 × 6
name id cost value1 value2 value3
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 a 1 10 1 1 1
2 b 4 45 1 1 1
3 b 5 70 2 2 2
现在,假设要比较的列数非常大(&gt; 10)。所有列均以 value
开头,因此我们可以具有 value_something,value_otherthing,value_morthing
,即,不一定像本示例一样。但是,如果列的数量为 n
,我必须天真地创建 n *(n -1)/2
比较,这显然是无法管理的。
是否有类似
df %>% filter(all_same(starts_with("value")))
all_same()
比较所有选定的列, start_with() (或任何其他选择器)?
rowwise> rowwise()
和
也没有帮助我太多。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以使用
if_all
将列从'value2'到'value3'上循环,请检查列值是否与value1
,if_all
相等。仅对于所有列比较为true-oftup
或我们要使用
start_with
的行,返回true。We may use
if_all
to loop over the columns from 'value2' to 'value3', check if the column values are equal withvalue1
,if_all
returns TRUE only for a row where all the column comparisons are TRUE-output
Or if we want to use
starts_with
这是一个可能的基本R选项,我们可以计算唯一值的数量,以查看每行是否只有1个(仅针对“值”列)。
或另一个选项是使用
startswith
选择以“值”(而不是索引)开头的列。输出
Here's a possible base R option, where we can count the number of unique values to see if there is only 1 for each row (and just for the "value" columns).
Or another option is to use
startsWith
to select the columns that start with "value" (instead of indices).Output