1

I am a newbie to R programming recently.

I want to transform the existing matrix form to new one.

The matrix that I have as follows,

data()

    1       2       3       4       5       6
1   0.60!   0.29!   1.42!   0.64    1.06    1.02 
2   1.33!   0.68!   1.44!   1.44    1.05    1.03 
3   0.60    0.67@   0.64    1.37    2.40    1.00 
4   1.37    0.29    1.43    0.63    1.05    2.32 
5   1.39    0.68    1.40    1.46    1.06    1.02 
6   0.63    0.68    0.61    1.46    1.74    1.05 
7   1.39    0.68    1.01    0.65    2.43    2.27 
.... 

I've listed the first line with '!' And '@' for easy understanding.

What I want to is,

vari()

    1       2       3       4       5       6       7
1   0.60!   0.29!   1.42!   1.33!   0.68!   1.44!   0.67@ 
2   0.29    1.42    0.64    0.68    1.44    1.44    0.64 
3   1.42    0.64    1.06    1.44    1.44    1.05    1.37 
4   0.64    1.06    1.02    1.44    1.05    1.03    2.40 
5   1.33    0.68    1.44    0.60    0.67    0.64    0.29                        
6                           
….      

I would like to list the data in the 1:2 rows and 1:3 columns in one line and locate the (3,2)value to (1,7) in vari matrix.

I think it would be work with the for-loop. I made the code, however, it is my first time to make it. So, it doesn't work well.

This is my trial....

x=matrix(nrow = nrow(data)-2, ncol = 8);

for ( i in 1:(nrow(data)))
{ for ( j in 1:(ncol(data)))
{
  x[i,j]<-((c(as.vector(t(as.matrix(data[i:i+1,j:j+2]))),data[i+2,j+1])))
}
}
x

however, it represent the following sentence

"Error in data[i:i + 1, j:j + 2] : subscript out of bounds"

Please help me!!!

1
  • 1
    When you use j+2 or j+1 and similarily I+1 , i+2, for the last column or last row, it gets more 1 or 2 added more than that in the dataset dimensions. You could either change the code to 1:(nrow(data)-2) similarly for j (not tested) Commented Nov 14, 2017 at 2:46

1 Answer 1

1

You needed to improve your indexing into the second data frame, I have added the n counter for this.

x=matrix(nrow = nrow(data)-2, ncol = 7);

n=1
for ( i in 1:(nrow(data)-3)){ 
  for ( j in 1:(ncol(data)-2)){
    x[n,]<-c(t(data[i:(i+1),j:(j+2)]),data[i+2,j+1])
    n=n+1
  }
}

 x
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0.60 0.29 1.42 1.33 0.68 1.44 0.67
[2,] 0.29 1.42 0.64 0.68 1.44 1.44 0.64
[3,] 1.42 0.64 1.06 1.44 1.44 1.05 1.37
[4,] 0.64 1.06 1.02 1.44 1.05 1.03 2.40
[5,] 1.33 0.68 1.44 0.60 0.67 0.64 0.29

Also be careful i:i+1is different to i:(i+1) which is what you were after.

Sign up to request clarification or add additional context in comments.

2 Comments

geeee............ I really had a great help sir.... Thank you So much!!! thank you and thank you again!!
That's great! Feel free to accept the answer if it worked for you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.