'How can I gather different columns into one in R? [duplicate]
I have some geographical data that kinda looks like this:
| name | x1 | x2 | x3 | x4 | y1 | y2 | y3 | y4 |
|---|---|---|---|---|---|---|---|---|
| Mark | 5 | 2 | 1 | 2 | 0 | 3 | 2 | 5 |
| Amy | 0 | 5 | 1 | 5 | 0 | 3 | 2 | 5 |
And I would like to transform it into something like this to graph it easier on ggplot:
| name | x | y |
|---|---|---|
| Mark | 5 | 0 |
| Mark | 2 | 3 |
| Mark | 1 | 2 |
| Mark | 2 | 5 |
| Amy | 0 | 0 |
| Amy | 5 | 3 |
| Amy | 1 | 2 |
| Amy | 5 | 5 |
I have tried the function gather() without any success.
Any help is appreciated.
Solution 1:[1]
It should be easier with pivot_longer which is a successor of gather.
tidyr::pivot_longer(df,
cols = -name,
names_to = '.value',
names_pattern = '([a-z])\\d+')
# name x y
# <chr> <int> <int>
#1 Mark 5 0
#2 Mark 2 3
#3 Mark 1 2
#4 Mark 2 5
#5 Amy 0 0
#6 Amy 5 3
#7 Amy 1 2
#8 Amy 5 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ronak Shah |
