简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM