-1

I am trying to reorder a database by loop but it does not work for me. There is too much data to do it one by one.

fact <- rep (1:2 , each = 3)
t1 <- c(2006,2007,2008,2000,2001,2002)
t2 <- c(2007,2008,2009,2001,2002,2004)
var1 <- c(56,52,44,10,32,41)
var2 <- c(52,44,50,32,41,23)
db1 <- as.data.frame(cbind(fact, t1, t2, var1, var2))
db1

fact   t1   t2 var1 var2
1    1 2006 2007   56   52
2    1 2007 2008   52   44
3    1 2008 2009   44   50
4    2 2000 2001   10   32
5    2 2001 2002   32   41
6    2 2002 2004   41   23

I need it to stay this way:

factor <-  rep (1:2 , each = 4)
t <- c(2006,2007,2008,2009,2000,2001,2002,2004)
var <- c(56,52,44,50,10,32,41,23)
db2 <- as.data.frame(cbind(factor, t, var))
db2

factor    t var
1      1 2006  56
2      1 2007  52
3      1 2008  44
4      1 2009  50
5      2 2000  10
6      2 2001  32
7      2 2002  41
8      2 2004  23

very thanks

mikhail-t
  • 4,103
  • 7
  • 36
  • 56
  • You want to arrange the whole dataset based on t column right? – Rana Usman Mar 09 '18 at 17:07
  • (1) this is not a database (which is typically a sql server or similar), it's a `data.frame`. (2) this is not (just) *"ordering"*, this is *"reshaping"*. If you search (either on SO or at google) for `R reshape dataframe`, you'll likely find something useful (perhaps the [`tidyr`](https://cran.r-project.org/web/packages/tidyr/index.html) or [`reshape2`](https://cran.r-project.org/web/packages/reshape2/index.html) packages). – r2evans Mar 09 '18 at 17:22
  • On closer inspection (cued by [nate.edwinton's answer](https://stackoverflow.com/a/49199463/3358272)), I think it is not reshaping as much as it is just `rbind` and column indexing. I suggest you use one of nate's first two offerings. – r2evans Mar 09 '18 at 18:16

1 Answers1

0
dat1 <- as.data.frame(cbind(fact, t1, var1))
names(dat1) <- c("fact", "t", "var")
dat2 <- as.data.frame(cbind(fact, t2, var2))
names(dat2) <- c("fact", "t", "var")
rbind.data.frame(dat1, dat2)
   fact    t var
1     1 2006  56
2     1 2007  52
3     1 2008  44
4     2 2000  10
5     2 2001  32
6     2 2002  41
7     1 2007  52
8     1 2008  44
9     1 2009  50
10    2 2001  32
11    2 2002  41
12    2 2004  23

Or

dat <- db1
names(dat) <- c("fact", rep("t", 2), rep("var", 2))
rbind(dat[,c(1,2,4)], dat[,c(1,3,5)])
   fact    t var
1     1 2006  56
2     1 2007  52
3     1 2008  44
4     2 2000  10
5     2 2001  32
6     2 2002  41
7     1 2007  52
8     1 2008  44
9     1 2009  50
10    2 2001  32
11    2 2002  41
12    2 2004  23

Or, as indicated, have a look at the reshape2 package - melt would certainly be of use, e.g.

library(reshape2)
dat <- db1
names(dat) <- c("fact", rep("t", 2), rep("var", 2))
rbind(melt(dat[,c(1,2,4)], id.vars = c("fact","t"), value.name = "var"),
      melt(dat[,c(1,3,5)], id.vars = c("fact","t"), value.name = "var")
)
niko
  • 5,253
  • 1
  • 12
  • 32