0

I have a dataframe named a whose column names are x1,y1,x2,y2,x3,y3. And how can I reshape it to a dataframe with column names as x,y without using loop, using tidyr::gather and tidyr::spread is preferred.

i.e.

a<-structure(list(X1 = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 0L, 0L, 0L), 
Y1 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 0L, 0L, 0L), X2 = 0:9, 
Y2 = c(2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 8L, 7L), X3 = c(0L, 
1L, 2L, 3L, 4L, 5L, 6L, 7L, 0L, 0L), Y3 = c(3L, 4L, 5L, 6L, 
7L, 8L, 9L, 8L, 0L, 0L)), .Names = c("X1", "Y1", "X2", "Y2", 
"X3", "Y3"), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10"))

want to be:

structure(list(x = c(0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 1, 2, 3, 
4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 0, 0), y = c(1, 2, 
3, 4, 5, 6, 7, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 3, 4, 5, 
6, 7, 8, 9, 8, 0, 0)), .Names = c("x", "y"), row.names = c(NA, 
-30L), class = "data.frame")
Michael
  • 41,989
  • 11
  • 82
  • 128
Minyi Han
  • 807
  • 1
  • 8
  • 15

2 Answers2

1

Try this:

reshape(data = a,direction = "long",varying = list(c(1,3,5),c(2,4,6)),v.names = c("x","y"))[,-c(1,4)]
tushaR
  • 3,083
  • 1
  • 20
  • 33
0

A solution using and .

library(dplyr)
library(tidyr)

a2 <- a %>%
  mutate(ID = 1:n()) %>%
  gather(Column, Value, -ID) %>%
  separate(Column, into = c("Letter", "Number"), sep = 1) %>%
  spread(Letter, Value) %>%
  arrange(Number, ID) %>%
  select(x = X, y = Y)
a2
#    x y
# 1  0 1
# 2  1 2
# 3  2 3
# 4  3 4
# 5  4 5
# 6  5 6
# 7  6 7
# 8  0 0
# 9  0 0
# 10 0 0
# 11 0 2
# 12 1 3
# 13 2 4
# 14 3 5
# 15 4 6
# 16 5 7
# 17 6 8
# 18 7 9
# 19 8 8
# 20 9 7
# 21 0 3
# 22 1 4
# 23 2 5
# 24 3 6
# 25 4 7
# 26 5 8
# 27 6 9
# 28 7 8
# 29 0 0
# 30 0 0
www
  • 38,575
  • 12
  • 48
  • 84