通过无序的列组合对 tibble 行进行分组
给定以下小标题,
tibble(sample = c(1:6),
string = c("ABC","ABC","CBA","FED","DEF","DEF"),
x = c("a","a","b","e","d","d"),
y = c("b","b","a","d","e","e"))
# A tibble: 6 × 4
sample string x y
<int> <chr> <chr> <chr>
1 1 ABC a b
2 2 ABC a b
3 3 CBA b a
4 4 FED e d
5 5 DEF d e
6 6 DEF d e
我想按列 x,y
的无序组合对行进行分组,然后翻转 x
⇔ y
并反转 string
在 x,y
相对于组中第一行反转的情况下。所需的输出:
# A tibble: 6 × 5
sample string x y group
<int> <chr> <chr> <chr> <dbl>
1 1 ABC a b 1
2 2 ABC a b 1
3 3 ABC a b 1
4 4 FED e d 2
5 5 FED e d 2
6 6 FED e d 2
Given the following tibble
tibble(sample = c(1:6),
string = c("ABC","ABC","CBA","FED","DEF","DEF"),
x = c("a","a","b","e","d","d"),
y = c("b","b","a","d","e","e"))
# A tibble: 6 × 4
sample string x y
<int> <chr> <chr> <chr>
1 1 ABC a b
2 2 ABC a b
3 3 CBA b a
4 4 FED e d
5 5 DEF d e
6 6 DEF d e
I would like to group rows by the unordered combination of columns x,y
, then flip x
⇔ y
and reverse string
in instances where x,y
is inverted relative to the first row in the group. The desired output:
# A tibble: 6 × 5
sample string x y group
<int> <chr> <chr> <chr> <dbl>
1 1 ABC a b 1
2 2 ABC a b 1
3 3 ABC a b 1
4 4 FED e d 2
5 5 FED e d 2
6 6 FED e d 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
先前的答案
这是一种同时使用
tidyverse
和apply
方法的方法。首先,对 x 和 y 列的行进行排序,然后对 x 和 ygroup_by
进行排序,如有必要,创建cur_group_id
和stri_reverse
。Previous answer
Here's a way using both
tidyverse
andapply
approaches. First, sort the rows of columns x and y, thengroup_by
x and y, create acur_group_id
andstri_reverse
if necessary.