0

I am trying to make a $n\times 4$ matrix by retrieving the n-th four elements in a given vector. Since I am new to R, don't know how to use loop functions properly.

My code is like

x<-runif(150,-2,2)
x1<-c(0,0,0,0,x)
for (i in 0:150)
 {ai<-x1[1+i,4+i]
 }

However, I got: Error in x1[1 + i, 4 + i] : incorrect number of dimensions.

I also want to combine these ai into a matrix, and each ai will be the i+1-th row of the matrix. Guess I should use the cbind function?

Any help will be appreciated. Thanks in advance.

3
  • I guess you got the error because your input data is vector and the indexing ie. [1+i, 4+i] is for matrices/data.frames etc. Could you show the expected result? Commented Oct 10, 2014 at 10:49
  • What would the expected result look like? Commented Oct 10, 2014 at 10:59
  • @akrun @ Roman Luštrik Commented Oct 10, 2014 at 12:31

2 Answers 2

1

You can do this directly with the matrix command:

x <- 1:36

xmat<-matrix(x,nr=9,byrow=TRUE)
Sign up to request clarification or add additional context in comments.

Comments

0

May be this helps:

n <- length(x1)-1
res <- sapply((4:n)-3, function(i) x1[(i+3):i])
dim(res)
#[1]   4 150

3 Comments

@ Roman Luštrik @akrun Let $X1=(0,0,0,0,a1,....,a150)$, then my matrix is like row1 = (0,0,0,0), row2=(a1,0,0,0),row3=(a2,a1,0,0),row4=(a3,a2,a1,0),row5=(a4,a3,a2,a1),....,row150=(a149,a148,a147,a146). So n-th row of the matrix consists of the n-th four elements of the vector X1, and it is in reverse order. Also a150 is left out. The dimension of the matrix is $x\times 150$.
I tried n<-length(x1)-1 res<-sapply((4:n)-3,function(i) x1[(i+3):i]), and it worked somehow. Thanks!
@Xst67 Yes, I guess that should do it. I was away from the computer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.