Home > OS >  How to combine columns with the same ID using R?
How to combine columns with the same ID using R?

Time:12-29

I want to Combine V1 and V2 with the matching ID number using R. What's the simplest way to go about it?

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

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

CodePudding user response:

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

CodePudding user response:

Try using pivot_longer with names_to = NULL to remove the unwanted column.

tidyr::pivot_longer(df, V1:V2, values_to = "V3", names_to = NULL)

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
  •  Tags:  
  • r
  • Related