我有一个名为a的数据框,其列名为x1,y1,x2,y2,x3,y3。我怎样才能将其重新整形为数据框,其列名为x,y而不使用循环,使用tidyr :: gather和tidyr :: spread是首选。
即。
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"))
希望成为:
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")
答案 0 :(得分:1)
试试这个:
reshape(data = a,direction = "long",varying = list(c(1,3,5),c(2,4,6)),v.names = c("x","y"))[,-c(1,4)]
答案 1 :(得分:0)
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