how to reshape the matrix with or without do loop?

#1
Dear All,
I need to reshape below matrix with or without do loop:
Below is my question:

PHP:
fd=read.table(header=TRUE, text="
 X1            X2            X3         X4           X5        X6
18.25766 123.9019 151.4487  34.1252 196.6713 231.2289
16.89285 121.7344 146.5685  60.4828 299.1966 346.6185
16.89592 121.7838 146.8924 100.7940 434.8895 497.1740
16.77895 121.5924 146.4672 158.7474 606.2282 684.8299
")
#I need to rehape this matrix maybe with do loop or without do loop:
#my final matrix should look like:
18.25766   34.1252 
16.89285   60.4828 
16.89592   100.7940  
16.77895   158.7474 
123.9019   196.6713
121.7344   299.1966  
121.7838   434.8895   
121.5924   606.2282
151.4487   231.2289  
146.5685   346.6185
146.8924   497.1740
146.4672   684.8299

#My approach is belew but the output misses the second component:
gg=data.frame(fd[,1],fd[,4])
kk=matrix(0,12,2)
for(i in 1:2){
              kk=data.frame(fd[,i],fd[,i+3])
              kk=rbind(gg,kk)
              }
If somebody can fix my error in function or guide me without do loop, I will greatly appreciate.
 
Last edited:

Dason

Ambassador to the humans
#2
Just so we're clear you want to stack these columns so that we get a matrix this has the following form?

X1 X2
X4 X5
X3 X6

Can I ask what the logic is behind this structure?
 
#3
Actually it is below:
X1 X4
X2 X5
X3 X6
PHP:
 week=c(1,2,3,4,5,6,7)
totalsales=c(45,47,49,51,53,66,72)
total=data.frame(week,totalsales)
modelt1=Arima(total[,2],order=c(1,0,0))
modelt2=Arima(total[,2],order=c(2,0,0))

#for each id
id=c(1,1,1,1,1,1,1,2,2,2,2,2,2,2)
week=c(1,2,3,4,5,6,7,1,2,3,4,5,6,7)
sales=c(20,21,22,23,24,30,32,25,26,27,28,29,36,40)
df=data.frame(id,week,sales)
h=2
fore1=function(x) {
  model1=Arima(x,model=modelt1)
  model2=Arima(x,model=modelt2)
  for1=forecast(model1,h)
  for2=forecast(model2,h)
  return(list(for1$mean,for2$mean))
}

ff_1=by(df[,3],df$id, function(x) fore1(x))
fd=data.frame(do.call(cbind, sapply(ff_1, "[", 1)),do.call(cbind, sapply(ff_1, "[", 2)))
#Here is why I need to reshape it:
id week  for1     for2 
1   7   43.63794  50.71540  
1   8   49.43388  61.52589
2   7   47.62211  53.2332
2   8   51.41809  59.8200
 

trinker

ggplot2orBust
#6
masarimk,

May I suggest that if you make edits to your post that you include a nore saying what you've done.

SOmething like...

EDIT I changed this future reader...

As it stands now Dason's comment doesn't make sense in that you changed your original post without mentioning so. Future readers won't understand the context of the situation and may be confused.