[英]How to combine columns with the same ID using R?
I want to Combine V1
and V2
with the matching ID number using R. What's the simplest way to go about it?我想使用 R 将
V1
和V2
与匹配的 ID 号组合起来。关于它的 go 最简单的方法是什么?
Below is an example how I want to combine my data.下面是我想如何组合数据的示例。 Hopefully this makes sense if not I can try to be more clear.
希望这是有道理的,如果不是我可以试着说得更清楚。 I did try the group by but I dont know if thats the best way to go about it
我确实尝试了 group by 但我不知道这是否是最好的方式 go 关于它
ID V1 V2
1 3 2
2 3 4
3 5 1
3 2 3
4 2 3
4 5 7
4 1 3
This is what I would like it to look like这就是我想要的样子
ID V3
1 3
1 2
2 3
2 4
3 5
3 1
3 2
3 3
4 2
4 3
4 5
4 7
4 1
4 3
You may try你可以试试
library(dplyr)
reshape2::melt(df, "ID") %>% select(ID, value) %>% arrange(ID)
ID value
1 1 3
2 1 2
3 2 3
4 2 4
5 3 5
6 3 2
7 3 1
8 3 3
9 4 2
10 4 5
11 4 1
12 4 3
13 4 7
14 4 3
Try using pivot_longer
with names_to = NULL
to remove the unwanted column.尝试使用
pivot_longer
with names_to = NULL
来删除不需要的列。
tidyr::pivot_longer(df, V1:V2, values_to = "V3", names_to = NULL)
Output: Output:
# ID V3
# <int> <int>
# 1 1 3
# 2 1 2
# 3 2 3
# 4 2 4
# 5 3 5
# 6 3 1
# 7 3 2
# 8 3 3
# 9 4 2
# 10 4 3
# 11 4 5
# 12 4 7
# 13 4 1
# 14 4 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.