根据 R 中的模式重新格式化数据
我希望你能帮助我解决这个问题,我有以下这样的数据:
ID,colour
1,base_yellow
1,blue
1,base_red
1,blue
1,pink
1,blue
1,base_yellow
2,base_yellow
2,blue
2,base_red
2,blue
2,pink
2,blue
2,base_yellow
3,base_yellow
3,blue
3,pink
3,blue
3,base_yellow
4,base_yellow
4,blue
4,green
4,blue
4,green
4,blue
4,pink
4,blue
4,base_yellow
每次与base(base_yellow,base_red)见面时,它都会创建新的组,预期的输出如下所示,它给出了一个新变量:
ID,colour
1,base_yellow; blue; base_red
1,base_red; blue; pink;blue;base_yellow
2,base_yellow; blue; base_red
2,base_red; blue; pink;blue; base_yellow
3,base_yellow;blue;pinkblue;base_yellow
4,base_yellow; blue;green;blue;green;blue;pink;blue;base_yellow
I hope you can help me with this problem, I have the following data like this:
ID,colour
1,base_yellow
1,blue
1,base_red
1,blue
1,pink
1,blue
1,base_yellow
2,base_yellow
2,blue
2,base_red
2,blue
2,pink
2,blue
2,base_yellow
3,base_yellow
3,blue
3,pink
3,blue
3,base_yellow
4,base_yellow
4,blue
4,green
4,blue
4,green
4,blue
4,pink
4,blue
4,base_yellow
Every time meet with base (base_yellow, base_red), it creates new group, the output that is expected as shown below, which gives a new variable:
ID,colour
1,base_yellow; blue; base_red
1,base_red; blue; pink;blue;base_yellow
2,base_yellow; blue; base_red
2,base_red; blue; pink;blue; base_yellow
3,base_yellow;blue;pinkblue;base_yellow
4,base_yellow; blue;green;blue;green;blue;pink;blue;base_yellow
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以根据自己的需要进行调整。
首先,创建一个向量
vec
,其中包含colour
以“base”开头的行位置。然后,您可以使用
purrr
中的map2_dfr
来提供基于vec
从开始位置到结束位置的颜色
。这将有助于解决最终在多行中使用相同颜色
的情况。在此步骤中还创建了分组变量group
。按
group
分组后,您可以仅保留具有多个colour
的colour
组,并用str_c
折叠它们一起为同一个组
。输出
This is something you might be able to adapt for your needs.
First, create a vector
vec
that includes row positions wherecolour
starts with "base".Then, you can use
map2_dfr
frompurrr
that will providecolour
that ranges from start to end positions based onvec
. This will help with situations where the samecolour
is used in more than one row in the end. A grouping variablegroup
is also created in this step.After grouping by
group
, you can keep onlycolour
groups that have more than onecolour
andstr_c
to collapse them together for the samegroup
.Output
试试这个:
结果:
Try this:
Results: