2016-05-02 3 views
1

bekomme ich meine Daten von breit zu lange umgestaltet, aber ich kann die Bestellung direkt nicht erhalten:R: Reshape von breit zu lang, nicht um rechts

data <- as.data.frame(matrix(c(rep(1:5),0,0,0,5,1,0,0,0,5,0),5,3)) 
colnames(data) <- c("id", "x1.a", "x3.a") 
print(data) 

# id x1.a x3.a 
# 1 1 0 0 
# 2 2 0 0 
# 3 3 0 0 
# 4 4 5 5 
# 5 5 1 0 

reshaped <- reshape(data, 
        varying = 2:3, 
        v.names = "x.a", 
        times = c(1,3), 
        timevar = "time", 
        idvar = "id", 
        direction = "long") 
print(reshaped) 

#  id time x.a 
# 1.1 1 1 0 
# 2.1 2 1 0 
# 3.1 3 1 0 
# 4.1 4 1 5 
# 5.1 5 1 1 
# 1.3 1 3 0 
# 2.3 2 3 0 
# 3.3 3 3 0 
# 4.3 4 3 5 
# 5.3 5 3 0 

ich die Werte in x1.a will und x3.a von id gruppiert werden, etwa so:

#  id time x.a 
# 1.1 1 1 0 
# 1.3 1 3 0 
# 2.1 2 1 0 
# 2.3 2 3 0 
# 3.1 3 1 0 
# 3.3 3 3 0 
# 4.1 4 1 5 
# 4.3 4 3 5 
# 5.1 5 1 1 
# 5.3 5 3 0 

Kann jemand helfen? Vielen Dank.

Antwort

1

Sie meinen, Sie möchten nur den Datenrahmen sortieren? Denn das ist ziemlich einfach:

> reshaped[with(reshaped,order(id,time)),] 
    id time x.a 
1.1 1 1 0 
1.3 1 3 0 
2.1 2 1 0 
2.3 2 3 0 
3.1 3 1 0 
3.3 3 3 0 
4.1 4 1 5 
4.3 4 3 5 
5.1 5 1 1 
5.3 5 3 0 
+0

Richtig, natürlich .. Danke! –